11

Is it at all possible?

#include <array>
#include <initializer_list>

struct A
{
    A ( std::initializer_list< int > l )
        : m_a ( l )
    {
    }

    std::array<int,2> m_a;
};

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

But this results in this error:

t.cpp: In constructor ‘A::A(std::initializer_list<int>)’:
t.cpp:7:19: error: no matching function for call to ‘std::array<int, 2ul>::array(std::initializer_list<int>&)’
         : m_a ( l )
                   ^
t.cpp:7:19: note: candidates are:
In file included from t.cpp:1:0:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: std::array<int, 2ul>::array()
     struct array
            ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   candidate expects 0 arguments, 1 provided
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int, 2ul>::array(const std::array<int, 2ul>&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘const std::array<int, 2ul>&’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int, 2ul>::array(std::array<int, 2ul>&&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘std::array<int, 2ul>&&’
qdii
  • 12,505
  • 10
  • 59
  • 116
  • This isn't possible, as a workaround, manually copy the elements of the `initializer_list`: `A (std::initializer_list l) /*Don't initialize m_a*/ { std::copy(l.begin(),l.end(),m_a.begin());}` – Mankarse Mar 19 '15 at 11:38
  • note that this is not special to constructors; the same issue arises with `std::initializer_list x = { 1, 2 }; std::array m { ?????? };` . You can only put things here that are a part of aggregate initialization, i.e. initializers for each element one by one. – M.M Mar 19 '15 at 11:49
  • See http://stackoverflow.com/q/5549524/1436796 which also provides a possible solution, even if the member array should be qualified `const` (which disqualifies leaving it empty and then copying the list contents later). – Marc van Leeuwen Mar 19 '15 at 12:37

1 Answers1

15

Not in this case. You can initialize array with a list-initializer

std::array<int, 2> a{1,2};

but you cannot initialize array with initializer_list, since array is just an aggregate type with only the default and copy constructor.

You can just leave the array empty and then copy the contents of the initializer_list into it.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
ForEveR
  • 55,233
  • 2
  • 119
  • 133