[英]Extracting tuple nested in a tuple using std::tie in c++11 using standard library
There's a function whose return type is std::tuple, bool>.有一个 function,它的返回类型是 std::tuple, bool>。 I would like to extract the values using std::tie directly to num1, num2 and bool_val.
我想使用 std::tie 直接将值提取到 num1、num2 和 bool_val。 Please note that I want to use std library directly.
请注意,我想直接使用 std 库。 I have helper code to unpack it (prefer to avoid using it if c++11 std lib already allows for something like this to be done.)
我有帮助代码来解压它(如果 c++11 标准库已经允许这样做,最好避免使用它。)
Is it possible to just use std::tie to extract the values as seen below using the standard library (cpp11)?是否可以使用标准库(cpp11)仅使用 std::tie 提取如下所示的值? Is the syntax wrong?
语法错了吗? I am trying to understand why it does not work.
我试图理解为什么它不起作用。
#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;
}
Can someone please explain this code snippet from cppreference for me?有人可以为我解释一下 cppreference 中的这段代码吗? It is a possible implementation for std::tie ( https://en.cppreference.com/w/cpp/utility/tuple/tie )
这是 std::tie 的可能实现( https://en.cppreference.com/w/cpp/utility/tuple/tie )
template <typename... Args>
auto tie(Args&... args) {
return std::tuple<Args&...>(args...);
}
Fundamentally, std::tie()
creates a tuple of references from references passed to it.从根本上说,
std::tie()
从传递给它的引用创建一个引用元组。 The issue you are running into is that references cannot bind to temporaries.您遇到的问题是引用不能绑定到临时对象。 Your
std::tie(n1, n2)
returns a temporary std::tuple<int&, int&>
and cannot be bound to std::tuple<int&, int&>&
as a parameter to the next std::tie()
.您的
std::tie(n1, n2)
返回一个临时std::tuple<int&, int&>
并且不能绑定到std::tuple<int&, int&>&
作为下一个std::tie()
的参数。
To make this work, you will have to make an intermediate std::tuple<int&, int&>
for it to bind to:要完成这项工作,您必须制作一个中间
std::tuple<int&, int&>
以使其绑定到:
std::tuple<int&, int&> nested = std::tie(n1, n2);
std::tie(nested, b) = SomeFunc();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.