【发布时间】:2015-11-08 18:30:26
【问题描述】:
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++ 中的元组元组?
【问题讨论】:
-
你可以做一个temporary tuple for nesting,虽然它看起来不那么好看。