Search code examples
c++c++11initializationstdarray

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?


Solution

  • 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