在 C++ 中解包嵌套元组

Unpacking nested tuples in C++

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

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

auto tup1 = std::make_tuple(1, 2, 3);
std::tie(a, b, c) = tup1;

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

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

在 C++ 中是否有一种惯用的方法来解压元组的元组?

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

template <class T>
constexpr T &lvalue(T &&v) {
    return v;
}

然后就可以这样使用了:

std::tie(a, b, c, lvalue(std::tie(d, e, f))) = tup2;

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