gpt4 book ai didi

c++ - 结构化绑定(bind),引用?是否可以删除它们

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:48 24 4
gpt4 key购买 nike

假设我有这样一个元组。

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

我想做这样的事情:

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

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

最佳答案

这个结构化绑定(bind)等价于:

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

tuple类型为 std::tuple<int&, int> , 这也是 e 的类型.

结构化绑定(bind)语法无法从 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

关于c++ - 结构化绑定(bind),引用?是否可以删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com