根据Derived中的值检查Base类的模板参数

mst*_*rft 1 c++ inheritance interface

让我们假设我有一个接口类(伪造的例子,而不是真正的代码)

template <int year>
class Car {
public: 
  virtual void move(double x, double y) = 0;
  // etc etc
};
Run Code Online (Sandbox Code Playgroud)

和许多派生类一样

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
};
Run Code Online (Sandbox Code Playgroud)

我选择了某个地方的模型

Car<foo>* myCar;    
switch (bar) {
  case 1: myCar = new model3434<foo>(); break;
  case 2: myCar = new model8295<foo>(); break;
  // etc
}
Run Code Online (Sandbox Code Playgroud)

我想在编译时检查Car的模板参数(或更好:派生类的模板参数).我希望模板参数年保持在一定范围内(即在yearMin和yearMax之间).但是:这个特定范围在派生类之间有所不同.(编辑:) 由于有很多派生类,我更喜欢Car内的解决方案.

我怎么能实现这种行为?或者这是一个糟糕的设计?

任何帮助表示赞赏.

Col*_*mbo 6

你是说这个吗?

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
};
Run Code Online (Sandbox Code Playgroud)

演示.
使用当前方法不可能将其放入基类中; CRTP不起作用,因为派生类在内部被认为是不完整的Car.但是,结构的改变可能会有所帮助.

template <int year>
class Car
{
    // Your implementation, as above
};

template <int year,
          int YearMin,
          int YearMax>
class CarChecker : Car<year>
{
    // Optionally declare constants here

    static_assert( YearMin <= year && year <= YearMax,
                   "Invalid template argument specified!" );
};

template <int year>
class Model8556 :
    public CarChecker<year, 1990, 2000> // Specify the minimum and maximum here
{};
Run Code Online (Sandbox Code Playgroud)