Я хотел бы получить тип в вариативном шаблоне по индексу. Индекс указывается в качестве аргумента шаблона. Мне удалось найти «хак», который работает, но я считаю, что он не в духе вариативного программирования шаблонов. Кроме того, он использует дополнительную память.
Вот код с некоторыми пояснениями:
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::declval<std::tuple<std::function<std::unique_ptr<InputPortTypes> (int)>...>>()
вместоthis->InputPortsTuple
, если только я что-то не упустил. (Я знаю, что это не то, что вам действительно нужно. Это просто немного менее плохая альтернатива.) - person   schedule 19.04.2015std::get<N>(tuple)
возвращает ссылку lvalue, которую вы можете назначить без каких-либо проблем. - person   schedule 19.04.2015