获取 std::tuple 的一部分

2022-01-19 00:00:00 tuples g++ c++ c++11

我有一个未知大小的元组(它是方法的模板参数)

I have a tuple of unknown size (it's template parametr of method)

有没有办法得到它的一部分(我需要扔掉它的第一个元素)

Is it way to get part of it (I need throw away first element of it)

例如,我有 tuple(7,12,42).我想要 tuple<int,int>(12,42) 这里

For example, I have tuple<int,int,int>(7,12,42). I want tuple<int,int>(12,42) here

推荐答案

借助编译时整数列表:

#include <cstdlib>

template <size_t... n>
struct ct_integers_list {
    template <size_t m>
    struct push_back
    {
        typedef ct_integers_list<n..., m> type;
    };
};

template <size_t max>
struct ct_iota_1
{
    typedef typename ct_iota_1<max-1>::type::template push_back<max>::type type;
};

template <>
struct ct_iota_1<0>
{
    typedef ct_integers_list<> type;
};

我们可以简单地通过参数包扩展来构造尾部:

We could construct the tail simply by parameter-pack expansion:

#include <tuple>

template <size_t... indices, typename Tuple>
auto tuple_subset(const Tuple& tpl, ct_integers_list<indices...>)
    -> decltype(std::make_tuple(std::get<indices>(tpl)...))
{
    return std::make_tuple(std::get<indices>(tpl)...);
    // this means:
    //   make_tuple(get<indices[0]>(tpl), get<indices[1]>(tpl), ...)
}

template <typename Head, typename... Tail>
std::tuple<Tail...> tuple_tail(const std::tuple<Head, Tail...>& tpl)
{
    return tuple_subset(tpl, typename ct_iota_1<sizeof...(Tail)>::type());
    // this means:
    //   tuple_subset<1, 2, 3, ..., sizeof...(Tail)-1>(tpl, ..)
}

用法:

#include <cstdio>

int main()
{
    auto a = std::make_tuple(1, "hello", 7.9);
    auto b = tuple_tail(a);

    const char* s = nullptr;
    double d = 0.0;
    std::tie(s, d) = b;
    printf("%s %g
", s, d);
    // prints:   hello 7.9

    return 0;
}

(在 ideone 上:http://ideone.com/Tzv7v;代码适用于 g++ 4.5 到 4.7和clang++ 3.0)

(On ideone: http://ideone.com/Tzv7v; the code works in g++ 4.5 to 4.7 and clang++ 3.0)

相关文章