How can I initialize the std :: array element of objects that do not have a standard constuctor?

Here is the code I'm having a problem with:

class Foo { public: Foo() : memberArray{Bar(1), Bar(3), Bar(2)} {} struct Bar { Bar(int param1) { } }; private: std::array<Bar,3> memberArray; // Bar memberArray[3]; // Using a raw array like this instead compiles fine.. }; 

I am using GCC 4.6.1 and compiling for C ++ 11. Does anyone know how I should initialize my std :: array?

+4
source share
4 answers

Since array<T, N> is actually a structure, a fully bound version requires {{ .. }} (internal to the array element of the object array<T, N> ). The spectrum does not allow the elimination of figures. He only allows this in the form declaration.

 Type var = { ... }; 

So you need to use a fully bound syntax

 Foo() : memberArray{{Bar(1), Bar(3), Bar(2)}} {} 

This is not a GCC bug, but required by the spec.

+5
source

As a workaround, you can return the function to an instance of this array.

 #include <array> class Foo { public: Foo() : memberArray(makeMemberArray()) {} struct Bar { Bar(int param1) { } }; private: std::array<Bar,3> memberArray; // Bar memberArray[3]; // Using a raw array like this instead compiles fine.. static std::array<Bar, 3> makeMemberArray() { std::array<Bar,3> a = {Bar(1), Bar(2), Bar(3)}; return a; } }; 

I think uniform initialization should allow what you do, except that the compiler cannot implement it.

+2
source

Based on Johannes Schaub - litb answer ... at least GCC will allow you to use shorthand syntax (excluding meaningless class name):

 Foo() : memberArray{{ {1}, {3}, {2} }} {} 

instead

 Foo() : memberArray{{Bar(1), Bar(3), Bar(2)}} {} 

I personally use something like the second version when I initialize an array of polymorphic pointers:

 Foo() : memberArray{{ dynamic_cast<Bar*>(new BarA(1)), dynamic_cast<Bar*>(new BarB(3)), dynamic_cast<Bar*>(new BarC(2)) }} {} 
0
source

Try this (it works for g ++ 4.5.2):

  Foo() : memberArray (std::array<Bar,3> {Bar(1), Bar(3), Bar(2)}) {} 
-4
source

Source: https://habr.com/ru/post/1388157/


All Articles