为什么= {}初始化不适用于元组? [英] Why ={} initialization doesn't work for tuple?

查看:124
本文介绍了为什么= {}初始化不适用于元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,pair只是tuple的特例,但以下内容令我感到惊讶:

To me a pair is just special case of a tuple, but following surprises me:

pair<int, int> p1(1, 2);   // ok
tuple<int, int> t1(1, 2);  // ok

pair<int, int> p2={1, 2};  // ok
tuple<int, int> t2={1, 2}; // compile error

为什么使用{}初始化tuple时会有区别?

Why there is difference when we use {} to initialize tuple?

我什至尝试g++ -std=c++1y,但仍然出现错误:

I tried even g++ -std=c++1y but still has error:

a.cc: In function 'int main()':
a.cc:9:29: error: converting to 'std::tuple<int, int>' from initializer list would use explicit constructor 'constexpr std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) [with _U1 = int; _U2 = int; <template-parameter-2-3> = void; _T1 = int; _T2 = int]'
     tuple<int, int> t2={1, 2};
                             ^

推荐答案

> c1>构造函数您要调用的是explicit,所以 复制列表初始化将会失败.相应的 pair构造函数不是explicit.

The tuple constructor you're trying to call is explicit, so copy-list-initialization will fail. The corresponding pair constructor is not explicit.

将代码更改为

tuple<int, int> t2{1, 2};

它将进行编译.

这篇关于为什么= {}初始化不适用于元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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