在C++中解压缩嵌套元组

dzh*_*lil 7 c++ tuples tie c++11

std::tie 提供了一种方便的方法,可以将C++中元组的内容解压缩为单独定义的变量,如下面的示例所示

int a, b, c, d, e, f;

auto tup1 = std::make_tuple(1, 2, 3);
std::tie(a, b, c) = tup1;
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有一个像下面这样的嵌套元组

auto tup2 = std::make_tuple(1, 2, 3, std::make_tuple(4, 5, 6));
Run Code Online (Sandbox Code Playgroud)

试图编译代码

std::tie(a, b, c, std::tie(d, e, f)) = tup2;
Run Code Online (Sandbox Code Playgroud)

失败并出错

/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;
                            ^
Run Code Online (Sandbox Code Playgroud)

有没有一种惯用的方法来解压缩C++中的元组元组?

Que*_*tin 4

当您知道没有风险时,可以通过以下辅助函数将右值引用转换为左值引用:

template <class T>
constexpr T &lvalue(T &&v) {
    return v;
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样使用它:

std::tie(a, b, c, lvalue(std::tie(d, e, f))) = tup2;
Run Code Online (Sandbox Code Playgroud)

在您的情况下,这样做确实没有问题,因为内部元组只需在语句持续时间内保持活动状态,而且情况确实如此。

  • 或者只使用“forward_as_tuple”。 (4认同)