Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ initializer lists and variadic templates

I wanted to create an array:

template < typename T, typename ... A > struct a {
  T x [1 + sizeof... (A)];
  a () = default;
  a (T && t, A && ... y) : x { t, y... } {}
};

int main () {
  a < int, int > p { 1, 1 }; // ok
  a < a < int, int >, a < int, int > > q { { 1, 1 }, { 3, 3 } }; // error: bad array initializer
}

Why doesn't it compile? (tested with g++ 4.6)

like image 310
Thomas Avatar asked Mar 29 '11 15:03

Thomas


People also ask

What is Variadic template in C++?

A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.

What is std :: Initializer_list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .

What is a parameter pack C++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

I'm pretty sure that's a bug. {} can be used in place of () for supplying the constructor with arguments. Therefore your code should be ok:

int main ()
{
    // this is fine, calls constructor with {1, 1}, {3, 3}
    a<a<int, int>, a<int, int>> q({ 1, 1 }, { 3, 3 });

    // which in turn needs to construct a T from {1, 1},
    // which is fine because that's the same as:
    a<int, int>{1, 1}; // same as: a<int, int>(1, 1);

    // and that's trivially okay (and tested in your code)

    // we do likewise with A..., which is the same as above
    // except with {3, 3}; and the values don't affect it
}

So the whole thing should be okay.

like image 97
GManNickG Avatar answered Oct 12 '22 11:10

GManNickG