List initializer to initialize a 2D element std :: array

How to initialize a nested (2D) std::array through a list of initializers?

 template <std::size_t W, std::size_t H> class Block { std::array<std::array<int, W>, H> block; public: template <typename ...E> Block(E&&...e) : block {{std::forward<E>(e)...}} {} }; 

The Block class should initialize the Block member as follows:

 Block<3, 2> b {{ {1, 2, 3}, {4, 5, 6} }}; 

Note. We have the ability to initialize std::array directly in C ++ 11:

 std::array<std::array<int, 3>, 2> b {{ {1, 2, 3}, {4, 5, 6} }}; 

I am using gcc-4.9.0

+6
source share
2 answers

The rules for braces are very complex when it comes to nested structures.

The simplest form of your code would be the following:

 Block<3, 2> b {1, 2, 3, 4, 5, 6}; 

This basically omits all internal braces; these omissions are allowed by language.

The following syntax, which is a bit complicated, is this:

 Block<3, 2> b {{1, 2, 3, 4, 5, 6}}; 

He still omits the braces, but as far as Block and as his member, he is FULLY fixed. It omits curly braces for array and its members.

And this one is FULLY installed:

 Block<3, 2> b {{{ {{1, 2,3}}, {{4,5,6}} }}}; 

It is fixed for all internal structures.

All forms compile in order .

See my other answer for a detailed explanation:

+5
source

This may be due to the fact that the interpretation of the standard is too capricious with the number of brackets needed to initialize std::array . This fully copied version compiles without problems in GCC 4.8.1:

 Block<3, 2> b { { { { {1, 2, 3} }, { {4, 5, 6} } } } }; 

Strange, this version also compiles:

  Block<3, 2> b { {{ {1, 2, 3}, {4, 5, 6} } } }; 
+1
source

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


All Articles