sbabbi
sbabbi

Reputation: 11181

On initialization of non-aggregate structures

Consider the following code:

template<size_t head,size_t ... Dims> struct make_vec {
      typedef typename make_vec<Dims...>::type type[head];
};

template<size_t head> struct make_vec<head> {typedef float type[head];};

template<size_t ... Dims>
struct vec {
    typename make_vec<Dims...>::type _data;
};

Since the class vec is an aggregate, I can use brace-enclosed-initializer lists to initialize vec.

vec<3,3> foo = {{
    {1,2,3},
    {4,5,6},
    {7,8,9}
}};

If I add a constructor to my vec class (for example to allow the use of expression-template, which is my ultimate goal), this syntax is no longer allowed, since vec would not be an aggregate anymore.

In this case, the logic thing to do would be to use std::initializer_list; however, when I compile a code which uses this construct, I get a long assembly code even with optimization enabled (I use std::uninitialized_copy to copy from the initializer_list to my vec class data member).

I had no luck in using variadic templates to achieve the same result. What is the best way (i.e. good runtime performance and clear syntax) to initialize user-defined fixed-size multi array types?

Upvotes: 2

Views: 620

Answers (1)

Luc Danton
Luc Danton

Reputation: 35449

You can write a constructor taking

typename make_vec<Dims...>::type const&

which will allow user code to use the same style of initialization as if it were an aggregate. If you're using GCC this might need a recent version, like GCC 4.7.

I have no idea about the generated code however.

Upvotes: 3

Related Questions