Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an array's derived type accept aggregate initialization?

For example

class A : public std::array<int, 3>
{
};

And

A a{1, 2, 3}; // failed currently.

How to make an array's derived type accept aggregate initialization?

like image 412
user1899020 Avatar asked Feb 06 '23 19:02

user1899020


1 Answers

You could provide a variadic template constructor as follows:

class A : public std::array<int, 3> {
public:
  template<typename... Args> constexpr A(Args&& ...args) 
    : std::array<int, 3>{{std::forward<Args>(args)...}} {}
};

Live Demo

Edit:

The following version works also on Visual Studio:

class A : public std::array<int, 3> {
public:
    template<typename... Args> constexpr A(Args&& ...args) 
      : std::array<int, 3>(std::array<int,3>{std::forward<Args>(args)...}) {}
};

Live Demo

like image 144
101010 Avatar answered May 11 '23 16:05

101010