Search code examples
c++arraysc++11list-initialization

std::array copy construction using braces


Why doesn't the following code compile:

#include <array>

struct A
{
    std::array<size_t, 5> i_;

    A() {}

    A( A const& a)
    : i_{ a.i_ } {}
};

int main()
{
    A a1;
    A a2 = a1;

    return 0;
}

GCC 4.8.1 says

error: cannot convert 'const std::array' to 'long unsigned int' in initialization : i_{ a.i_ }


Solution

  • The problem is that std::array is an aggregate, hence you can not use curly brackets to call the copy-ctor. You would need to specify the elements. This also explains your error message, it is trying to convert the a.i_ to an element of the array, which is a size_t. Since you can not do that, you must use i_(a.i_) to create a copy.