问题描述
我想为可变参数模板类的每种类型提供函数重载。可以吗?
template<typename ...args>
class Example {
virtual void doSomething(args(0) arg) { ... }
virtual void doSomething(args(1) arg) { ... }
/// etc... implementations are the same,but I need access to the type
}
我尝试使用折叠表达式,但是我很确定自己的路线不正确。因为我需要虚函数,所以不能将它们声明为template<typename T> virtual void doSomething(T arg)
,因为不允许模板虚函数。
解决方法
您可以从基类模板的实例化模板化包中派生该类,该基类模板使用其单个模板参数作为函数参数类型来定义一个虚拟函数。 然后,派生类将保留所有都是虚拟的模板参数类型的函数重载。
template<typename arg>
class Base {
virtual void doSomething(arg arg) {}
};
template<typename ...args>
class Example : public Base<args>... {};