我们说我有这样一个元组。
std::tuple<int &, int> tuple{};
我想做那样的事情:
auto [i1, i2] = tuple; // Here i1 is lvalue reference, i2 is int
i1是左值引用,因为元组上的第一个值是一个左值引用。
但是,我没有写auto &[i1, i2]
。那么,有没有可能&#34;删除&#34;在这种情况下的参考?所以我把i1和i2作为&#34;简单&#34; INT。
谢谢!
答案 0 :(得分:3)
此结构化绑定相当于:
auto e = tuple;
auto&& i1 = e.get<1>();
auto&& i2 = e.get<2>();
由于tuple
的类型为std::tuple<int&, int>
,因此e
的类型也是tuple
。
结构化绑定语法没有从#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';
}
内部删除引用的风格。但是,您可以使用辅助函数来执行as in this question。这是一个有效的例子:
5 6
5 6
输出:
{{1}}