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

Why ={} initialization doesn't work for tuple?

对我来说 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};
                             ^

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

将您的代码更改为

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

它会编译。

除了 Praetorian's (我已投票)之外,我还想添加更多信息...

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

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

编译并具有预期的语义。这样做的提案是N4387。这也将允许构造如:

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

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

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