How to force a derived type array to accept aggregate initialization?

for instance

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

AND

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

How to make initialization of an aggregate derivative of type accept?

+4
source share
3 answers

You can provide the constructor of variation patterns 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 next version also works in 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

+7
source

EDIT: as other comments noted, this will not work for std::array, because it std::arraydoes not contain a constructor that accepts initializer_list. But this can be useful for other containers that have a constructor that accepts initializer_list, for example std::vector.

( ++ 11):

class A: public std::vector<int,3>
{
      using std::vector<int,3>::vector;
};
+1

:

A(std::array<int, 3>);

:

#include <array>
#include <iostream>

struct A : public std::array<int, 3>
{
    A(std::array<int, 3>    a) :
        std::array<int, 3>{a}
    {
    }
};

int main(void)
{
    A   a({1, 2, 3});

    std::cout << a[0] << "\n";
    std::cout << a[1] << "\n";
    std::cout << a[2] << "\n";
}

, " "...

0
source

All Articles