通过索引访问可变参数模板中的类型

2024-01-13

我想通过索引获取可变参数模板中的类型。索引被指定为模板参数。 我设法找到了一个有效的“黑客”,但我相信它不符合可变参数模板编程的精神。此外,它还使用额外的内存。

这是带有一些解释的代码:

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.

理想情况下,我想要N成为动态参数而不是模板参数。但是,我不确定这是否可能。


你可以简单地滥用std::tuple_element http://en.cppreference.com/w/cpp/utility/tuple/tuple_element:

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

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

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

是做同样事情的更好方法。不过,并非所有常见的编译器都知道这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过索引访问可变参数模板中的类型 的相关文章

随机推荐