我有一个类似于以下内容的课程:
class SomeClass
{
public:
template<typename... Args>
void doSomething(Args && ... args);
//... other methods etc.
};
然而,我真正想要的是有两种不同的SomeClass
。理想情况下,我能够从一个通用接口派生出来SomeOtherClass
,但我需要有一个不同的实现doSomething
并且模板化方法不能是虚拟的。我可以创建一个模板类,但是每个采用其中一个(并且有很多)的方法本身都必须是模板等。
我能想到的最好的办法就是实现这两种类型doSomething
在基类中,并让该方法调用虚拟方法来确定在运行时使用哪个方法。
有更好的解决方案吗?
进一步解释
我有很多与此类似的方法:
void foo(SomeClass * obj);
foo
calls obj->doSomething
这一切都很好,但是我后来意识到我需要一种不同的SomeClass
但希望它能够使用这些相同的方法,例如:
class SomeClass
{
public:
// This won't work
template<typename... Args>
virtual void doSomething(Args && ... args) = 0;
// ... other common methods
};
class TheFirstType
{
public:
template<typename... Args>
void doSomething(Args && ... args);
// ... other specific methods
};
class TheSecondType
{
public:
template<typename... Args>
void doSomething(Args && ... args);
// ... other specific methods
};
如果合法的话,上面的方法是理想的,但是虚拟方法不能模板化。到目前为止,我已经通过只绕过了这个限制doSomething
在基类中定义,但同时具有以下实现TheFirstType
and TheSecondType
由 if 语句分隔,该语句检查实例实际是什么类型:
template<typename... Args>
void SomeClass::doSomething(Args && ... args)
{
if (this->type() == FIRST_TYPE) {
// ... the implementation that should rightfully be part of TheFirstType
} else if (this->type() == SECOND_TYPE) {
// ... the implementation that should be part of TheSecondType
}
}
然而,这看起来很混乱,所以我想知道是否有更好的方法。