Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I initialize a boost::array?

Tags:

c++

boost

I am trying to understand the boost array. The code can be read easily from author's site.

In the design rationale, author (Nicolai M. Josuttis) mentioned that the following two types of initialization is possible.

boost::array<int,4> a = { { 1, 2, 3 } };  // Line 1
boost::array<int,4> a = { 1, 2, 3 };      // Line 2

In my experiment with g++ (version 4.1.2) Line 1 is working but Line 2 is not. (Line 2 yields the following:

warning: missing braces around initializer for 'int [4]'
warning: missing initializer for member 'boost::array<int, 4ul>::elems'

)

Nevertheless, my main question is, how Line 1 is working? I tried to write a class similar to array.hpp and use statement like Line 1, but that did not work :-(. The error is

typedef array< unsigned int, 10 > MyArray;

MyArray b = { { 1, 2, 3 } };  // Line 74

array_test.cpp:74: error: in C++98 'b' must be initialized by constructor, not by '{...}'
array_test.cpp:74: error: no matching function for call to 'array<unsigned int, 10u>::array(<brace-enclosed initializer list>)'
array.h:16: note: candidates are: array<unsigned int, 10u>::array()
array.h:16: note:                 array<unsigned int, 10u>::array(const array<unsigned int, 10u>&)

Can somebody explain me? Is there some boost specific thing happening in Line 1 that I need to be aware of?

like image 490
Arun Avatar asked Apr 22 '10 01:04

Arun


1 Answers

this is a regular brace initialization list:

Boost array is defined like this:

struct array { T elems[N]; };

inner brace is for elems array initialization, outear brace is for struct initialization. If you provide your own constructor, you no longer have plain old datatype any cannot initialize using brace

notice that you can go without outer brace, but you will get a warning

like image 184
Anycorn Avatar answered Sep 21 '22 06:09

Anycorn