首页 > 解决方案 > 使用标准库在 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...);
}

标签: c++

解决方案


从根本上说,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(); 

推荐阅读