1

I am trying to initialize data_ private class data member which is a C++11 array of length 3 with the initializer list constructor:

template<typename Type>
class triElement 
{
    public: 

        triElement(std::initializer_list<Type> list)
            :
                data_(list)
        {}

        auto begin() const
        {
            return data_.begin(); 
        }

        auto end() const
        {
            return data_.end(); 
        }

    private:

        std::array<Type, 3> data_; 
}; 

And the compilation of the complete code example fails with the error:

g++ -std=c++1y -O2 -Wall -pedantic -pthread main.cpp && ./a.out

main.cpp: In instantiation of 'triElement<Type>::triElement(const std::initializer_list<_Tp>&) [with Type = int]':

main.cpp:80:31:   required from here

main.cpp:37:27: error: no matching function for call to 'std::array<int, 3ul>::array(const std::initializer_list<int>&)'

                 data_(list)

Even though exactly the same approach works when the attribute data is of type std::vector:

template<typename Type>
class elements 
{
    public: 

        elements(std::initializer_list<Type> list)
            :
                data_(list)
        {}

        auto begin() const
        {
            return data_.begin(); 
        }

        auto end() const
        {
            return data_.end(); 
        }

    private:

        std::vector<Type> data_; 
}; 

Is there something special I need to think of when delegating the initializer list constructor call to the C++11 array attribute?

tmaric
  • 5,347
  • 4
  • 42
  • 75
  • 2
    `std::array` is required to be an aggregate, so it cannot have any constructors that would convert from `initializer_list` to `array`. You can for example wrap the array or use some metaprogramming trickery to get the elements out of the `initializer_list` and initialize the elements of the `array`. – dyp Jul 24 '14 at 15:26
  • If your class must be initialized from exactly 3 elements, I don't think an `initializer_list` constructor is appropriate. Those ctors are for initializing with an *arbitrary* number of elements. – dyp Jul 24 '14 at 15:28
  • first comment: cool, thanks a lot. second comment: I get it now, thx. – tmaric Jul 24 '14 at 15:53

0 Answers0