根据派生中的值检查基类的模板参数

Check template argument of Base class against values in Derived

本文关键字:基类 参数 检查 派生      更新时间:2023-10-16

假设我有一个接口类(虚构的示例,而不是真正的代码),例如

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(或更好的:派生类)的模板参数。我希望模板参数年份保持在一定范围内(即在 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
};

演示。
使用当前方法无法将其放入基类中;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
{};
相关文章: