Variadic模板展开到std :: tuple

时间:2015-06-11 08:18:13

标签: c++ templates c++11 variadic-templates

我有一个过滤器类,它有两个模板参数,输入数和输出数。

template<int Ins, int Outs>
class Filter
{
    // implementation
};

有时我需要将多个过滤器串联起来,所以我想将它们包装在一个类

template<int... args>
class Chain
{
};

这样当我使用链

Chain<5, 10, 25, 15> chain;

它将args展开为一个元组,在Chain类中以类似的方式结束

std::tuple<Filter<5, 10>, Fiter<10, 25>, Filter<25, 15>> filters;

这样的事情可能吗?我对这些概念还是比较陌生的,并且无法绕过它。

3 个答案:

答案 0 :(得分:9)

我们可以在三行中执行此操作而不进行递归:

template<int... args>
struct Chain
{
    // put args... into a constexpr array for indexing
    static constexpr int my_args[] = {args...};

    // undefined helper function that computes the desired type in the return type
    // For Is... = 0, 1, ..., N-2, Filter<my_args[Is], my_args[Is+1]>...
    // expands to Filter<my_args[0], my_args[1]>,
    //            Filter<my_args[1], my_args[2]>, ...,
    //            Filter<my_args[N-2], my_args[N-1]>

    template<size_t... Is>
    static std::tuple<Filter<my_args[Is], my_args[Is+1]>...>
                helper(std::index_sequence<Is...>);

    // and the result
    using tuple_type = decltype(helper(std::make_index_sequence<sizeof...(args) - 1>()));
};

strtotime

答案 1 :(得分:5)

我们可以使用一些递归模板魔术来做到这一点:

//helper class template which will handle the recursion
template <int... Args>
struct FiltersFor;

//a helper to get the type of concatenating two tuples
template <typename Tuple1, typename Tuple2>
using tuple_cat_t = decltype(std::tuple_cat(std::declval<Tuple1>(),
                                            std::declval<Tuple2>())); 

//pop off two ints from the pack, recurse
template <int Ins, int Outs, int... Others>
struct FiltersFor<Ins,Outs,Others...>
{
    //the type of concatenating a tuple of Filter<Ins,Outs> with the tuple from recursion
    using type = tuple_cat_t<std::tuple<Filter<Ins,Outs>>, 
                             typename FiltersFor<Outs,Others...>::type>;    
};

//base case, 1 int left
template <int Dummy>
struct FiltersFor<Dummy>
{
    using type = std::tuple<>;
};

//for completeness
template <>
struct FiltersFor<>
{
    using type = std::tuple<>;
};

//our front-end struct
template<int... args>
using Chain = typename FiltersFor<args...>::type;

或者,我们可以删除单个int和无int版本并定义主模板,如下所示:

template <int... Args>
struct FiltersFor
{
    using type = std::tuple<>;
};

现在我们可以这样测试:

static_assert(std::is_same<Chain<1,2,3,4>, std::tuple<Filter<1,2>,Filter<2,3>,Filter<3,4>>>::value, "wat");
static_assert(std::is_same<Chain<1,2>, std::tuple<Filter<1,2>>>::value, "wat");
static_assert(std::is_same<Chain<>, std::tuple<>>::value, "wat");

Demo

答案 2 :(得分:0)

我已经遇到了类似的问题,最终得到了一个运算符*,用于类过滤器接受Filter<Ins1, Ins>对象并构建Filter<Ins1, Outs>

template<int Ins, int Outs>
class Filter
{
    template <int Ins1>
    Filter<Ins1, Outs> operator*(const Filter<Ins1, Ins> &rhs) const
    {
    // implementation
    }
};

现在的问题是:你的过滤器做了什么?组成成为可能(也许我偏向于在我的上下文中Filter是一个函数而在我的情况下operator *是函数组合的事实)