对我来说,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/