展开到std :: tuple的可变模板 [英] Variadic template unrolling to std::tuple

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

问题描述

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

I have a filter class that takes two template parameters, the number of inputs and the number of outputs.

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

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



Sometimes I need to chain multiple filters in series so I was thinking to wrap them in a class

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

以便在我使用链时

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

它将args展开成一个元组,在Chain类中结束这样的操作

it unrolls the args into a tuple to end up with something like this in the Chain class

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

这样的事情可能吗?

推荐答案

我们可以在三行中做到这一点没有递归:

We can do this in three lines and no recursion:

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>()));
};

演示

这篇关于展开到std :: tuple的可变模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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