根据派生中的值检查基类的模板参数
Check template argument of Base class against values in Derived
假设我有一个接口类(虚构的示例,而不是真正的代码),例如
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
{};
相关文章:
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 命名参数习惯用法和(抽象)基类
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如何允许模板参数中的类类型,仅当它有两个基类时
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 根据参数数调用 mixin 基类的构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 在C++单元测试上下文中,抽象基类是否应将其他抽象基类作为函数参数
- C++ 如何使派生类自动获取基类参数
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 将函数上调整到基类参数的另一个
- 将派生类对象传递给具有 C++ 中基类参数的函数时,为什么要传递引用而不是值?
- 如何使用派生类中的虚拟函数,该函数在另一个具有基类参数的类中声明
- 将基类 2 参数构造函数调用到子类 1 参数构造函数中
- 指向友元函数中基类参数类型的指针
- 按值传递共享指针并接受作为基类参数是如何工作的
- 为带有基类参数的派生类参数调用函数重载