如何子类化模板化基类? [英] How to subclass a templated base class?
本文介绍了如何子类化模板化基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据结构:
struct fastEngine { ... }
struct slowEngine { ... }
template<typename T>
class Car {
T engine;
vector<T> backupEngines;
virtual void drive() = 0;
}
class FastCar : public Car<fastEngine> {
virtual void drive() {
// use the values of "engine" in some way
}
}
class SlowCar : public Car<slowEngine> {
virtual void drive() {
// use the values of "engine" in some way
}
}
Car* getCarFromCarFactory() { // 1
if (randomNumber == 0)
return new FastCar();
else
return new SlowCar();
}
void main() {
Car* myCar = getCarFromCarFactory(); // 2
myCar->drive();
}
编译器在位置1和2处抱怨,因为它要求我定义 Car * ,带有模板参数。我不在乎我正在使用的 Car 的模板版本,我只想要一个指向 Car 的指针,我可以开车。 引擎结构必须是结构,因为它们来自现有代码而我无法控制它们。
The compiler complains at locations 1 and 2 because it requires that I define Car* with template parameters. I don't care what templated version of Car I'm using, I just want a pointer to a Car that I can drive. The engine structs must be structs because they are from existing code and I don't have control over them.
推荐答案
你可以创建一个非模板化的基类 Car< T>
继承,例如
You could create a non-templated base class that Car<T>
inherits, e.g.
struct ICar {
virtual void drive() = 0;
};
template <typename T>
class Car : public ICar {
// ...
}
int main() { // BTW, it's always `int main`, not `void main`
ICar *myCar = getCarFromCarFactory();
myCar->drive();
}
这篇关于如何子类化模板化基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文