2
votes

I want initialize base class with std::initializer_list.

struct A : public std::array<int, 4>
{
  // This constructor works fine
  A()
  : std::array<int, 4>{{ 1, 2, 3, 4 }}
  {
  }

  // THIS CONSTRUCTOR FAILS TO COMPILE
  A(std::initializer_list<int> il)
  : std::array<int, 4>{il}
  {
  }
};

GCC error for second constructor is

error: array must be initialized with a brace-enclosed initializer

What I want is to initialize new A instance with initializer_list like this

A var{{ 1, 2, 3, 4 }}

and pass it to base class.

2

2 Answers

2
votes

The class std::array has no constructor taking a std::initializer_list.

The only way you have is to do it like this :

#include <array>
#include <initializer_list>

struct A : public std::array<int, 4>
{
    A()
    : std::array<int, 4>{{ 1, 2, 3, 4 }}
    {
    }

    A(std::array<int, 4> il)
    : std::array<int, 4>(il)
    {
    }
};

int main ()
{
    A a ({{ 1, 2, 3, 4 }});
}
0
votes

It's saying that an array can be initialized with a "brace-enclosed initializer" as in your first ctor, but not with an initializer_list as in your second. There is no array ctor that takes an initializer_list. In fact, there are no ctors for arrays except for the implicitly-declared special member functions.