通过索引访问可变参数模板中的类型 [英] Access a type in a variadic template by index

查看:61
本文介绍了通过索引访问可变参数模板中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过索引获取可变参数模板中的类型.索引被指定为模板参数.我设法找到了一个可行的"hack",但我认为这不符合可变参数模板编程的精神.此外,它使用额外的内存.

I would like to obtain a type in a variadic template by index. The index is specified as a template argument. I managed to find a 'hack' that works, but I believe that it is not in the spirit of variadic template programming. Besides, it uses extra memory.

下面是带有一些解释的代码:

Here is the code with some explanations:

template <typename... InputPortTypes>
class PipelineReceiver
{

protected:

    // This tuple is used for storing types only
    // Hence, I would like to get rid of it, but I am not sure how.
    std::tuple<
    std::function<std::unique_ptr<InputPortTypes> (int)>...
    > InputPortsTuple;

    // This vector is used for storing the actual objects
    // This is needed to be able to access/change its elements
    // during run time later on.
    // The vector is used for storage of function pointers (i.e. of type std::function)
    // that represent methods of another object upstream the pipeline.
    std::vector<boost::any> InputPortsVector;

public:

    PipelineReceiver()
        {
            // create an empty vector of the required size
            InputPortsVector.resize(sizeof...(InputPortTypes));
        }

    void connectPorts(int InputPortIndex, boost::any c_OutputPort)
        {
            // connect ports
            InputPortsVector[InputPortIndex] = c_OutputPort;
        }

     // this function needs to be modified to avoid using InputPortsTuple
    template<int N>
    void getInputPortValue(void)
        {
            std::cout <<
                *boost::any_cast<decltype(std::get<N>(this -> InputPortsTuple))>(
                    InputPortsVector[N]
                    )(0) <<
                std::endl;
        }

};

我想删除对象 InputPortsTuple 并将其替换为某种形式的递归过程,以推断 getInputPortValue 中的类型.

I would like to remove the object InputPortsTuple and replace it with some form of a recursive procedure for inferring the types in getInputPortValue.

理想情况下,我希望 N 是动态参数,而不是模板参数.但是,我不确定是否可行.

Ideally, I would like N to be a dynamic parameter instead of a template argument. However, I am not sure if this is possible.

推荐答案

您可以简单地滥用

You could simply abuse std::tuple_element:

typename std::tuple_element<N, std::tuple<InputPortTypes...>>::type

注意:如果可以使用C ++ 14,

Note: if you can use C++14,

std::tuple_element_t<N, std::tuple<InputPortTypes...>>

是执行相同操作的更好方法.不过,并非所有普通的编译器都知道它.

is a nicer way to do the same thing. Not all common compilers know it yet, though.

这篇关于通过索引访问可变参数模板中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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