【发布时间】:2016-07-17 11:22:15
【问题描述】:
我正在尝试编写一个处理程序类,当给定一个元组时,它可以动态处理给定元组中的特定字段。
问题是,我不知道如何创建该类的实例,因为该类是模板化的,而实例化所需的模板在元组内。
(由于与问题无关的设计请求,将处理程序放在单独的类中很重要)
注意ILevelHandler 实例中的???,我需要提供模板,但我不知道该怎么做。
#include <tuple>
#include <string>
#include <iostream>
#include <boost/variant.hpp>
template <typename... T>
class ILevelHandler
{
public:
virtual void HandleEnterLevel(const boost::variant<T...>& _value)
{
std::cout << " value: " << _value << std::endl;
}
};
int main()
{
std::tuple<int, float, std::string, int> tpl {4, 6.6, "hello", 7};
ILevelHandler<???> lvl(tpl);
for (size_t i = 0; i < 4; ++ i)
{
lvl.HandleEnterLevel(i, dynamic_get(i, tpl));
}
return 0;
}
值得一提的是:使用未封装在类中的函数来解决问题很容易,但我需要提供一个抽象类,以便用户必须自己实现该函数。
【问题讨论】:
-
您已经证明不需要将包编码为
ILevelHandler的类型 -struct ILevelHandler { template<typename... T> void HandleEnterLevel(boost::variant<T...> const& v) { std::cout << " value: " << v << '\n'; } };有什么问题? -
没什么问题,其实好像是个解决办法。
-
我会纠正自己 - 这不是一个解决方案,因为“ILevelHandler”函数应该是虚拟的,因此不能是模板函数。
标签: c++ templates c++11 tuples variadic-templates