c – `std :: tuple`有什么用?

这里(https://stackoverflow.com/a/37550660/34509)用户@Barry在评论部分注释,你可以使用std :: tuple< int [2]>并且显然禁止实例化这种类型.我还没有听说过这个野兽,我想知道它有什么用途,而不是直接存储int var [2]或者使用std :: array< int,2>.

据说,std :: tuple< int [2]>不可复制,既不可移动也不可转换为int var [2].它有什么其他用途?

最佳答案
我很确定这是未定义的行为.请参阅Requires and Returns子句:

tuple.creation-10 and 12说:

Requires: For all i, Ui shall be the type cvi tuple<Argsi...>, where
cvi is the (possibly empty) ith cv-qualifier-seq and Argsi is the parameter pack
representing the element types in Ui. Let
Aik be the kith type in Argsi. For all Aik the following requirements shall be satisfied: If Ti is deduced as an
lvalue reference type, then is_constructible<Aik, cvi Aik&>::value == true, otherwise is_constructible<Aik, cvi Aik&&>::value == true.

Returns: A tuple object constructed by initializing the kith type element eik in ei with get<ki>(std::forward<Ti>(tpi))
for each valid ki and each group ei in
order.

就像巴里所说,没有什么能阻止std :: tuple< int [2]>吨;但尝试对它做任何事情都可能导致编译器出现硬错误.例:

std::tuple<int[2]> t; // fine
std::tuple<int[2]> t{}; // fine

而:

std::tuple<int[2]> a() {
  int a[2] = { 1, 2};
  return std::tuple<int[2]>(a);
}

int main() {
   auto x = a();
   // ...
}

给出如下错误:

error: array initializer must be an initializer list
        : _M_head_impl(std::forward<_UHead>(__h)) { }

转载注明原文:c – `std :: tuple`有什么用? - 代码日志