c++ - 为什么 ={} 初始化不适用于元组?

标签 c++ c++11 tuples initializer-list list-initialization

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

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会有区别?

我什至尝试了 g++ -std=c++1y 但仍然有错误:

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};
                             ^

最佳答案

除了Praetorian's correct answer (我赞成),我想添加更多信息...

C++14 后,标准已更改为允许:

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

编译并具有预期的语义。这样做的建议是N4387 .这也将允许以下构造:

tuple<int, int>
foo()
{
    return {1, 2};
}

仅当 tuple 中的所有 T 都可以从所有参数中隐式构造时才允许。

作为一个不符合标准的扩展,libc++ 已经实现了这种行为。

关于c++ - 为什么 ={} 初始化不适用于元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084706/

相关文章:

c++ - C++中可能进行以下编译时编程任务

c++ - 与 std::condition_variable_any 相关的开销是多少

c++ - 继承私有(private)构造函数

c++ - 在 C++11 中解析毫秒日期时间的最佳方法是什么

python - 过滤包含元组的列表的列表

c++ - STL vector 如何提供随机访问

c++ - 随着时间 SFML C++ 移动时每隔几秒 Sprite

c++ - 使用 noexcept 运算符依赖

python - 遍历元组并计算数字的百分比

Python 按值将列表元素分组为元组