2

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 Answers 2

2

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 }});
}
Sign up to request clarification or add additional context in comments.

9 Comments

seems like std::initializer_list is implicitly casted to std::array here. Would this have a runtime performance impact?
It is not a std::initializer_list that is used here : std::array uses aggregate_initialization. Quoting cppreference : [std::array] combines the performance and accessibility of a C-style array with the benefits of a standard container [...]
@Chnossos, Although an array can be initialized with list initialization, it cannot be initialized with an actual initializer_list object. Try: auto il = {1,2,3}; array<int,3> a(il);
So should we use aggregate_initialization for fixed size things and initializer_list for variable sized things then?
@ShitImplementor You can only use an initializer_list object if there's a ctor that accepts one. As for the performance penalty, with move constructors it shouldn't be a problem.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.