如何从元组到元组中的元素的元组? [英] How to get from a tuple to a tuple of references to elements in the tuple?
本文介绍了如何从元组到元组中的元素的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C ++ 11元组,我想得到一个元组 std :: reference_wrapper
s到元组的相同元素。
I have a C++11 tuple, and I would like to get a tuple of std::reference_wrapper
s to the same elements of the tuple. Is there an easy way to do that?
感谢
推荐答案
通过一系列索引,很容易映射元组,例如:
Mapping a tuple is easy given a pack of indices, e.g.:
#include <tuple>
#include <functional>
#include <iostream>
template <int...>
struct Seq {};
template <int n, int... s>
struct Gens : Gens<n-1, n-1, s...> {};
template <int... s>
struct Gens<0, s...> {
typedef Seq<s...> Type;
};
// The above are taken from http://stackoverflow.com/q/7858817
使用索引,我们可以应用 std :: get
给元组的每个元素 c>:
Using the indices we could apply std::ref
to every element of the tuple using std::get
:
template <int... s, typename Tuple>
auto ref_tuple_impl(Seq<s...> seq, Tuple& tup)
-> std::tuple<
std::reference_wrapper<
typename std::tuple_element<s, Tuple>::type
>...
>
{
return std::make_tuple(std::ref(std::get<s>(tup))...);
}
template <typename Tuple>
auto ref_tuple(Tuple& tup)
-> decltype( ref_tuple_impl(typename Gens<std::tuple_size<Tuple>::value>::Type>(), tup) )
{
return ref_tuple_impl(typename Gens<std::tuple_size<tuple>::value>::Type(), tup);
}
使用演示:
int main() {
auto t = std::make_tuple(1, 4.5, "66");
auto rt = ref_tuple(t);
std::get<0>(rt).get() = 123;
std::get<1>(rt).get() = 5.67;
std::get<2>(rt).get() = "34";
std::cout << std::get<0>(t) << std::endl;
std::cout << std::get<1>(t) << std::endl;
std::cout << std::get<2>(t) << std::endl;
}
这篇关于如何从元组到元组中的元素的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文