如何从元组到元组中元素的引用元组?

时间:2012-10-25 13:56:32

标签: c++ c++11 tuples

我有一个C ++ 11元组,我想在元组的相同元素中得到一个std::reference_wrapper元组。有没有一种简单的方法可以做到这一点?

由于

1 个答案:

答案 0 :(得分:3)

给定a pack of indices,例如:

,可以很容易地映射元组
#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 https://stackoverflow.com/q/7858817

使用索引我们可以使用std::refstd::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;
}