Variadic模板展开到std :: tuple

dom*_*vic 3 c++ templates variadic-templates c++11

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

template<int Ins, int Outs>
class Filter
{
    // implementation
};
Run Code Online (Sandbox Code Playgroud)

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

template<int... args>
class Chain
{
};
Run Code Online (Sandbox Code Playgroud)

这样当我使用链条时

Chain<5, 10, 25, 15> chain;
Run Code Online (Sandbox Code Playgroud)

它将args展开成一个元组,最终在Chain类中得到类似的结果

std::tuple<Filter<5, 10>, Fiter<10, 25>, Filter<25, 15>> filters;
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?我对这些概念很陌生,无法绕过它.

T.C*_*.C. 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>()));
};
Run Code Online (Sandbox Code Playgroud)

演示.


Tar*_*ama 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;
Run Code Online (Sandbox Code Playgroud)

或者,我们可以摆脱单个int和没有int版本并定义主模板,如下所示:

template <int... Args>
struct FiltersFor
{
    using type = std::tuple<>;
};
Run Code Online (Sandbox Code Playgroud)

现在我们可以这样测试:

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");
Run Code Online (Sandbox Code Playgroud)

演示