简体   繁体   English

如何子类化模板化的基类?

[英]How to subclass a templated base class?

I have the following data structures: 我有以下数据结构:

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();
}

The compiler complains at locations 1 and 2 because it requires that I define Car* with template parameters. 编译器在位置1和2处抱怨,因为它要求我使用模板参数定义Car * 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. 引擎结构必须是结构,因为它们来自现有代码,我无法控制它们。

You could create a non-templated base class that Car<T> inherits, eg 您可以创建Car<T>继承的非模板化基类,例如

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();
}

PiotrLegnica's answer is right, but I'd just like to add a few points: PiotrLegnica的答案是对的,但我想补充几点:

class templates are not classes 类模板不是类

In your code, Car is a class template. 在您的代码中,Car是一个类模板。 A class template is not a class, it is only ... a template from which classes can be defined, and different instantiations of a same template do not necessarily lead to types having the same interface. 类模板不是类,它只是...可以定义类的模板,同一模板的不同实例不一定导致具有相同接口的类型。 A simple example: 一个简单的例子:

template<class T>
class Foo
{
public:
  T Bar();
  bool Baz(const T&);
};

struct and class is (almost) the same thing struct和class(几乎)是一样的

The engine structs must be structs because they are from existing code and I don't have control over them. 引擎结构必须是结构,因为它们来自现有代码,我无法控制它们。

I assume that you wrote this because you were suspecting that the problem was related to the use of structs instead of classes as template parameters. 我假设你写了这个是因为你怀疑这个问题与使用结构而不是类作为模板参数有关。 This is not the case. 不是这种情况。 In C++, struct and class is almost the same thing. 在C ++中,struct和class几乎是一回事。 The only difference is that the default access and inheritance are public with a struct while they are private with a class. 唯一的区别是默认访问和继承是公共的结构,而它们是私有的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM