结构化绑定,参考?是否可以删除它们

structured bindings, reference ? Is it possible to remove them

假设我有这样一个元组。

std::tuple<int &, int> tuple{};

我想做这样的事情:

auto [i1, i2] = tuple; // Here i1 is lvalue reference, i2 is int

i1 是左值引用,因为元组中的第一个值是一个左值引用。 但是,我没有写auto &[i1, i2]。那么,在这种情况下是否有可能 "remove" 引用?这样我就得到了 i1 和 i2 作为 "simple" int。 谢谢!

此结构化绑定等同于:

auto e = tuple;  
auto&& i1 = e.get<1>();
auto&& i2 = e.get<2>();

因为 tuple 的类型是 std::tuple<int&, int>,那也是 e 的类型。

结构化绑定语法无法从 tuple 中删除引用。但是你可以创建一个辅助函数来做到这一点 as in this question。这是一个工作示例:

#include <tuple>
#include <iostream>

template <typename... T>
using tuple_with_removed_refs = std::tuple<typename std::remove_reference<T>::type...>;

template <typename... T>
tuple_with_removed_refs<T...> remove_ref_from_tuple_members(std::tuple<T...> const& t) {
    return tuple_with_removed_refs<T...> { t };
}

int main()
{
    int x{5}, y{6};

    std::tuple<int& , int> t(x, y);

    auto [i1, i2] = remove_ref_from_tuple_members(t);

    std::cout << i1 << ' ' << i2 << '\n';
    i1 = 7; i2 = 8;
    std::cout << x << ' ' << y << '\n';
}

输出:

5 6
5 6