Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C+中解包嵌套元组+; 代码> STD::TIG/提供了一种方便的方法,将C++中元组的内容解压缩到单独定义的变量中,如下面的示例说明 int a, b, c, d, e, f; auto tup1 = std::make_tuple(1, 2, 3); std::tie(a, b, c) = tup1;_C++_C++11_Tuples_Tie - Fatal编程技术网

在C+中解包嵌套元组+; 代码> STD::TIG/提供了一种方便的方法,将C++中元组的内容解压缩到单独定义的变量中,如下面的示例说明 int a, b, c, d, e, f; auto tup1 = std::make_tuple(1, 2, 3); std::tie(a, b, c) = tup1;

在C+中解包嵌套元组+; 代码> STD::TIG/提供了一种方便的方法,将C++中元组的内容解压缩到单独定义的变量中,如下面的示例说明 int a, b, c, d, e, f; auto tup1 = std::make_tuple(1, 2, 3); std::tie(a, b, c) = tup1;,c++,c++11,tuples,tie,C++,C++11,Tuples,Tie,但是,如果我们有一个嵌套的元组,如下所示 auto tup2 = std::make_tuple(1, 2, 3, std::make_tuple(4, 5, 6)); 正在尝试编译代码 std::tie(a, b, c, std::tie(d, e, f)) = tup2; 由于错误而失败 /tmp/tuple.cpp:10: error: invalid initialization of non-const reference of type ‘std::tuple<int&am

但是,如果我们有一个嵌套的元组,如下所示

auto tup2 = std::make_tuple(1, 2, 3, std::make_tuple(4, 5, 6));
正在尝试编译代码

std::tie(a, b, c, std::tie(d, e, f)) = tup2;
由于错误而失败

/tmp/tuple.cpp:10: error: invalid initialization of non-const reference of type ‘std::tuple<int&, int&, int&>&’ from an rvalue of type ‘std::tuple<int&, int&, int&>’
  std::tie(a, b, c, std::tie(d, e, f)) = tup2;
                            ^
/tmp/tuple.cpp:10:错误:从“std::tuple”类型的右值初始化“std::tuple&”类型的非常量引用无效
std::tie(a,b,c,std::tie(d,e,f))=tup2;
^

C++中有一种习惯性的解压缩元组元组吗?

< p>当你知道没有风险时,你可以通过下列帮助函数将rValk引用转换成LValk一:
template <class T>
constexpr T &lvalue(T &&v) {
    return v;
}

在您的例子中,这样做确实没有问题,因为内部元组只需要在语句的持续时间内保持活动状态,事实就是如此。

可能的重复您可以创建一个,尽管它看起来不太好看。是否可以定义一个复合函数
ltie
,其中调用
ltie(a,b,c)
相当于调用
lvalue(std::tie(a,b,c))
以将代码简化为
ltie(a,b,c,ltie(d,e,f))=tup2
;不幸的是,事实并非如此。如果将临时元组嵌入到函数中,那么它将是该函数的局部元组,并且不会存在足够长的时间。您可以将其改为宏。或者只使用
作为元组转发
std::tie(a, b, c, lvalue(std::tie(d, e, f))) = tup2;