如何绑两个元组?例如
std::tuple<int, char> a;
std::tuple<double> b;
是否可以编写一个返回my_tie(a, b)
的函数std::tuple<int&, char&, double&>
,以便在
my_tie(a, b) = make_tuple(1, 'a', 3.14);
a == std::tuple<int, char>{1, 'a'}
和b == std::tuple<double>{3.14}
。也就是说,my_tie
函数(与std :: tie不同)首先解开元组,然后将所有元素绑定在一起。
答案 0 :(得分:3)
(2014年12月29日更新为使用std::index_sequence_for
)
这是一个使用C ++ 14索引序列的解决方案:
#include <tuple>
#include <utility>
template <class... T1, class... T2,
std::size_t... i, std::size_t... j>
auto tie_helper(std::tuple<T1...>& t1, std::tuple<T2...>& t2,
std::index_sequence<i...>, std::index_sequence<j...>) {
return std::tuple<T1&..., T2&...> {std::get<i>(t1)..., std::get<j>(t2)...};
}
template <class... T1, class... T2>
auto tie(std::tuple<T1...>& t1, std::tuple<T2...>& t2) {
typedef std::index_sequence_for<T1...> s1;
typedef std::index_sequence_for<T2...> s2;
return tie_helper(t1, t2, s1{}, s2{});
}
答案 1 :(得分:3)
比@Brian的版本略胜一筹:
// construct a tuple of Ts&... from a tuple of Ts...
template <class... T, std::size_t... i>
auto to_tuple_ref_helper(std::tuple<T...>& t, std::index_sequence<i...>) {
return std::tuple<T&...> {std::get<i>(t)...};
}
template <class... T>
auto to_tuple_ref(std::tuple<T...>& t) {
return to_tuple_ref_helper(t, std::index_sequence_for<T...>());
}
// and a tuple containing a single reference from all other types
template <class T>
auto to_tuple_ref(T& t) {
return std::tuple<T&>{t};
}
// tuple_cat the tuples of references together
template <class... Ts>
auto flattening_tie(Ts &...args) {
return std::tuple_cat(to_tuple_ref(args)...);
}