C++ 对照派生类中的值检查基类的模板参数

C++ 对照派生类中的值检查基类的模板参数,c++,inheritance,interface,C++,Inheritance,Interface,让我们假设我有一个由示例组成的接口类,而不是像 template <int year> class Car { public: virtual void move(double x, double y) = 0; // etc etc }; 还有很多派生类,比如 template <int year> class Model8556 : virtual public Car<year> { private: void move(double

让我们假设我有一个由示例组成的接口类,而不是像

template <int year>
class Car {
public: 
  virtual void move(double x, double y) = 0;
  // etc etc
};
还有很多派生类,比如

template <int year>
class Model8556 : virtual public Car<year> {
private: 
  void move(double x, double y) {
    // ...
  }
  int yearMax = 2000; // different for every model
  int yearMin = 1990;
  // etc etc
};
我在某处选择了这个模型

Car<foo>* myCar;    
switch (bar) {
  case 1: myCar = new model3434<foo>(); break;
  case 2: myCar = new model8295<foo>(); break;
  // etc
}
我确实希望在编译时检查派生类的Car或更好的模板参数。我希望模板参数year保持在一定范围内,即yearMin和yearMax之间。但是:派生类之间的特定范围不同。编辑:因为有很多派生类,我更喜欢Car中的解决方案

我怎样才能做到这一点?还是这个设计不好

非常感谢您的帮助。

您是说这个吗

template <int year>
class Model8556 : virtual public Car<year> {
private: 

  static const int yearMax = 2000; // I assume you meant a static constant
  static const int yearMin = 1990;

  static_assert( yearMin <= year && year <= yearMax,        // Condition
                 "Invalid template argument specified!" );  // Error message
};
你是说这个吗

template <int year>
class Model8556 : virtual public Car<year> {
private: 

  static const int yearMax = 2000; // I assume you meant a static constant
  static const int yearMin = 1990;

  static_assert( yearMin <= year && year <= yearMax,        // Condition
                 "Invalid template argument specified!" );  // Error message
};

试试静态断言。您确定需要使用虚拟继承吗?@NO_NAME:与什么相反?你建议正常遗传吗?接口是否有经验法则?@mstrkrft。。。规则是,如果不需要,就不要使用虚拟继承。@mstrkrft虚拟继承在使用多重继承时最有用。请尝试静态断言。您确定需要使用虚拟继承吗?@NO_NAME:与什么相反?你建议正常遗传吗?接口是否有经验法则?@mstrkrft。。。规则是,如果不需要,则不使用虚拟继承。@mstrkrft虚拟继承在使用多重继承时最有用。我忘了说:我希望此检查位于基类内,因为有很多派生类。这可能吗?@mstrkrft提出了一个解决方案。实际上,这不适用于上述switch语句,因为Car指针需要他的模板参数。很抱歉,我以前没有正确地测试它。@mstrkrft再次检查第二个版本,我调整了它。我忘了说:我希望这个检查在基类内,因为有很多派生类。这可能吗?@mstrkrft提出了一个解决方案。实际上,这不适用于上述switch语句,因为Car指针需要他的模板参数。很抱歉,我以前没有正确测试它。@mstrkrft再次检查第二个版本,我调整了它