tuple vector and initializer_list

Need4Steed picture Need4Steed · Sep 15, 2012 · Viewed 30.6k times · Source

I tried to compile the following snippets with gcc4.7

vector<pair<int,char> > vp = {{1,'a'},{2,'b'}};
//For pair vector, it works like a charm.

vector<tuple<int,double,char> > vt = {{1,0.1,'a'},{2,4.2,'b'}};

However, for the vector of tuples, the compiler complains:

error: converting to ‘std::tuple’ from initializer list would use explicit constructor ‘constexpr std::tuple< >::tuple(_UElements&& ...) [with _UElements = {int, double, char}; = void; _Elements = {int, double, char}]’

The error info spilled by the compiler is total gibberish for me, and I have no idea how were the constructors of tuple implemented, yet I do know they're totally okay with uniform initialization (like: tuple<int,float,char>{1,2.2,'X'}), therefore, I wonder if the problem I encountered is only a TODO of the compiler or it's something defined by the C++11 standard.

Answer

Luc Danton picture Luc Danton · Sep 15, 2012

The relevant std::tuple constructors are explicit. This means that what you want to do is not possible, since the syntax you want to use is defined in terms of copy initialization (which forbids calling an explicit constructor). In contrast, std::tuple<int, float, char> { 1, 2.2, 'X' } uses direct initialization. std::pair does have non-explicit constructors only.

Either use direct-initialization or one of the Standard tuple factory function (e.g. std::make_tuple).