得到std :: tuple的一部分 [英] get part of std::tuple

查看:238
本文介绍了得到std :: tuple的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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< int,int,int>(7,12,42)。我想要 tuple 这里

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

推荐答案

p>在编译时整数列表的帮助下:

With help of a compile-time integer list:

#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\n", 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)

这篇关于得到std :: tuple的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆