c++ - 使用标准库在 c++11 中使用 std::tie 提取嵌套在元组中的元组
问题描述
有一个函数的返回类型是 std::tuple, bool>。我想使用 std::tie 直接将值提取到 num1、num2 和 bool_val。请注意,我想直接使用 std 库。我有帮助代码来解压它(如果 c++11 标准库已经允许这样做,最好避免使用它。)
是否可以使用标准库(cpp11)仅使用 std::tie 提取如下所示的值?语法错了吗?我试图理解为什么它不起作用。
#include <iostream>
#include <tuple>
using PosType = std::tuple<int, int>;
std::tuple<std::tuple<int, int>, bool> SomeFunc() {
return std::make_tuple(std::make_tuple(10, 12), true);
}
int main() {
int n1 = -1, n2 = -1;
bool b = false;
PosType temp;
// This line gives compilation error. Trying to understand why this might be wrong.
// std::tie(std::tie(n1, n2), b) = SomeFunc();
std::cout << n1 << " " << n2 << " " << b << " " << std::endl;
return 0;
}
有人可以为我解释一下 cppreference 中的这段代码吗?这是 std::tie 的可能实现(https://en.cppreference.com/w/cpp/utility/tuple/tie)
template <typename... Args>
auto tie(Args&... args) {
return std::tuple<Args&...>(args...);
}
解决方案
从根本上说,std::tie()
从传递给它的引用创建一个引用元组。您遇到的问题是引用不能绑定到临时对象。您std::tie(n1, n2)
返回一个临时的std::tuple<int&, int&>
,不能std::tuple<int&, int&>&
作为参数绑定到 next std::tie()
。
为了使这项工作,您必须制作一个中间体std::tuple<int&, int&>
以将其绑定到:
std::tuple<int&, int&> nested = std::tie(n1, n2);
std::tie(nested, b) = SomeFunc();
推荐阅读
- ssl - 使用 openssl 验证针对 CRL 的证书链
- javascript - 角 | 使用带有过滤器的新数据数组更新 mat-table
- android - 大小为 [0x0] 类 com.bumptech.glide.load.engine.GlideException 的 null 加载失败:收到 null 模型
- mysql - VB.net和Mysql登录问题使用两个表
- wordpress - 查找特定 WordPress 安装的路径
- python - pandas datetime dd.mm.yyyy 转换失败
- vue.js - 如何从 vue-router 的历史记录中排除路由?
- ios - 将 Var 数据作为委托传递时崩溃
- java - java.sql.Date 没有打印正确的日期
- web - 如何在 TeamCity 中使用 MSBuild 部署我的网站