结构化绑定和tie() [英] Structured binding and tie()
问题描述
给出以下声明:
int a[3] {10,20,30};
std::tuple<int,int,int> b {11,22,33};
我可以使用结构化绑定声明来解码 a
和 b
:
I can use structured binding declarations to decode a
and b
:
auto [x1,y1,z1] = a;
auto [x2,y2,z2] = b;
但是如果 x1
, y1
等已经存在,该怎么办?
But if x1
, y1
, etc. already exist, what do I do?
std::tie(x1,y1,z1) = a; // ERROR
std::tie(x2,y2,z2) = b; // OK
这适用于 b
,但不适用于 a
。是否有类似的简单构造适用于 a
,还是我必须获取 a [0]
,<$分别是c $ c> a [1] 和 a [2]
?
This works for b
but not for a
. Is there a similar simple construct that works for a
, or do I have to fetch a[0]
, a[1]
and a[2]
separately?
推荐答案
不是。
结构化绑定具有用于处理数组和某些其他类型的特定语言规则。 tie()
特别是 tuple< T& ...>
,并且只能从另一个 tuple< U& ...>
。
Structured bindings has specific language rules to handle arrays and certain other types. tie()
is specifically a tuple<T&...>
and can only be assigned from another tuple<U&...>
.
数组的情况下,您可以编写一个函数将该数组变成引用的元组:
With the array case, you can write a function to turn that array into a tuple of references into it:
template <typename T, size_t N, size_t... Is>
auto as_tuple_impl(T (&arr)[N], std::index_sequence<Is...>) {
return std::forward_as_tuple(arr[Is]...);
}
template <typename T, size_t N>
auto as_tuple(T (&arr)[N]) {
return as_tuple_impl(arr, std::make_index_sequence<N>{});
}
std::tie(x1, y1, z1) = as_tuple(a); // ok
或者,如果您知道有多少个绑定(无论如何都必须要绑定),您可以使用结构化绑定作为返回元组。但是,您必须同时指定大小并为每个大小写一个大小写:
Alternatively, if you know how many bindings there are (which you have to anyway), you can use structured bindings as give back a tuple. But you have to both specify the size and write out a case for each one:
template <size_t I, typename T>
auto as_tuple(T&& tuple) {
if constexpr (I == 1) {
auto&& [a] = std::forward<T>(tuple);
return std::forward_as_tuple(a);
} else if constexpr (I == 2) {
auto&& [a, b] = std::forward<T>(tuple);
return std::forward_as_tuple(a, b);
} else if constexpr (I == 3) {
// etc.
}
}
std::tie(x1, y1, z1) = as_tuple<3>(a); // ok
这篇关于结构化绑定和tie()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!