元组向量和 initializer_list [英] tuple vector and initializer_list

查看:37
本文介绍了元组向量和 initializer_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用 gcc4.7 编译以下代码片段

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:

错误:从初始化列表转换为std::tuple"将使用显式构造函数constexpr std::tuple<;>::tuple(_UElements&& ...) [with _UElements = {int, double, char};=无效;_Elements = {int, double, char}]'

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}]’

编译器溢出的错误信息对我来说完全是胡言乱语,我不知道元组的构造函数是如何实现的,但我知道它们完全可以使用统一初始化(例如:tuple<int,float,char>{1,2.2,'X'}),所以不知道我遇到的问题只是编译器的TODO还是C++11标准定义的问题.p>

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.

推荐答案

相关的std::tuple构造函数是explicit.这意味着您想要做的事情是不可能的,因为您想要使用的语法是根据复制初始化定义的(它禁止调用 explicit 构造函数).相比之下,std::tuple;{ 1, 2.2, 'X' } 使用直接初始化.std::pair 确实只有非explicit 构造函数.

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.

使用直接初始化或标准元组工厂函数之一(例如 std::make_tuple).

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

这篇关于元组向量和 initializer_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆