Discussion:
vector of tuples - uniform initialization
(too old to reply)
Giuseppe Remondo
2014-11-11 16:11:24 UTC
Permalink
Hello c.l.c++,

I'm quite new to C++. I'm a bit lost in understanding why
the definition of 'vt1' does not compile. Can you please
tell me which constructor is being called and why it's not
doing what I'd like it should?

#include <string>
#include <tuple>
#include <vector>

using std::string;
using std::tuple;
using std::make_tuple;
using std::vector;

int main()
{
tuple<string, int> t{"hello", 0}; //ok
vector<tuple<string, int>> vt1{{"hello", 0}}; //error
vector<tuple<string, int>> vt2{make_tuple("hello", 0)}; //ok
}
--
Gius
Vincenzo Mercuri
2014-11-11 19:41:24 UTC
Permalink
Post by Giuseppe Remondo
Hello c.l.c++,
I'm quite new to C++. I'm a bit lost in understanding why
the definition of 'vt1' does not compile. Can you please
tell me which constructor is being called and why it's not
doing what I'd like it should?
#include <string>
#include <tuple>
#include <vector>
using std::string;
using std::tuple;
using std::make_tuple;
using std::vector;
int main()
{
tuple<string, int> t{"hello", 0}; //ok
vector<tuple<string, int>> vt1{{"hello", 0}}; //error
vector<tuple<string, int>> vt2{make_tuple("hello", 0)}; //ok
}
In this case the tuple's constructor is explicit. While in:

tuple<string, int> t{"hello", 0};

you direct-initialize the object `t', which is exactly how you should
initialize an object of a type whose constructor is explicit, in:

vector<tuple<string, int>> vt1{{"hello", 0}};

while you are direct-initializing the vector, you are asking for an
implicit conversion from the initializer list {"hello", 0} to the
tuple<string, int> type. This triggers the error. You can get around
the problem in the way you've already seen with vt2, or also:

vector<tuple<string, int>> vt1{tuple<string, int>("hello", 0)};



#include <iostream>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

int main()
{
vector<tuple<string, int>> vt{tuple<string, int>("hello", 0)};
cout << get<0>(vt[0]) << endl;
cout << get<1>(vt[0]) << endl;
}
--
Vincenzo Mercuri
Loading...