gpt4 book ai didi

c++ - 继承模板方法

转载 作者:可可西里 更新时间:2023-11-01 16:37:51 27 4
gpt4 key购买 nike

我有一个类似于下面的类:

class SomeClass
{
public:
template<typename... Args>
void doSomething(Args && ... args);

//... other methods etc.
};

然而,我真正想要的是有两种不同的SomeClass。理想情况下,我可以从一个通用接口(interface)派生出 SomeOtherClass,但我需要有一个不同的 doSomething 实现,并且模板化方法不能是虚拟的。我可以制作一个模板化类,但是每个采用其中之一(并且有很多)的方法本身都必须是模板等。

我能想出的最好办法是在基类中实现两种类型的 doSomething 并让该方法调用虚拟方法来确定在运行时使用哪个。

有没有更好的解决方案?

进一步说明

我有很多看起来与此类似的方法:

void foo(SomeClass * obj);

foo 调用 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 来绕过这个限制,但是 TheFirstTypeTheSecondType 的实现是分开的通过检查实例实际类型的 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
}
}

然而,这看起来很困惑,所以我想知道是否有更好的方法。

最佳答案

我认为@stijn 的回答是正确的;你有一个理想的案例 CRTP .你可以选择根据那个改变你的逻辑。

template<class T>
class SomeClass
{
public:
template<typename... Args>
void doSomething(Args && ... args)
{
static_cast<T*>(this)->doSomething(...);
}
//other method can be virtual
virtual void foo ()
{
doSomething(...);
// ... other code;
}
};

现在只需将这些继承给您的其他子类:

class TheFirstType : SomeClass<TheFirstType>
{
public:
template<typename... Args>
void doSomething(Args && ... args) { ... }

virtual void foo ()
{
}
}; // do same for TheSecondType.

你已经完成了。

关于c++ - 继承模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6703199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com