I have the following code. Basically I want to initialize a std::array of non-POD structs using aggregate initialization syntax. Both g++ 4.6 and 4.7 (latest weekly snapshot) fails to compile the code.
#include <array>
struct TheClass {
int a1, a2;
TheClass(int b1, int b2) : a1{b1}, a2{b2} {};
};
template<unsigned D>
struct OtherClass {
std::array<TheClass, D> a;
OtherClass(std::array<TheClass, 2> b) : a{b} {};
};
int main()
{
OtherClass<2>{{ {1, 2}, {2, 3} }}; //tried a lot of options here
}
GCC errors:
v.cpp: In function ‘int main()’:
v.cpp:20:37: error: no matching function for call to ‘OtherClass<2u>::OtherClass(<brace-enclosed initializer list>)’
v.cpp:20:37: note: candidates are:
v.cpp:15:5: note: OtherClass<D>::OtherClass(std::array<TheClass, 2ul>) [with unsigned int D = 2u]
v.cpp:15:5: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘std::array<TheClass, 2ul>’
v.cpp:11:8: note: constexpr OtherClass<2u>::OtherClass(const OtherClass<2u>&)
v.cpp:11:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const OtherClass<2u>&’
v.cpp:11:8: note: constexpr OtherClass<2u>::OtherClass(OtherClass<2u>&&)
v.cpp:11:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘OtherClass<2u>&&’
My questions: is the above code correct? It seems that as std::array is an aggregate, there should be no problems to construct its data members. Maybe it’s a bug in GCC?
EDIT:
OtherClass<2>{{ TheClass{1, 2}, TheClass{2, 3} }}; works of course, but I don’t want to use that as I have to construct the class in a lot of places. C++11 should support omission of TheClass. Also see this question.
std::arrayis an aggregate containing an array, so you need an extra pair of braces to initialise it from a regular array:However, it seems that older versions of GCC still stuggle with this: 4.5.1 rejects it, while 4.6.1 accepts it.