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

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

推荐答案

<你试图调用的代码>元组构造函数是explicit,所以copy-list-initialization 将失败.对应的 pair 构造函数 不是 显式.

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

它会编译.

相关文章