当我看到使用的 CRTP 模式时,似乎在基类型中调用的函数名总是指向派生类型中不同名称的实现函数(例如:foo()
在基类中调用 static_cast<DerivedType*>(this)->foo_implementation();
.
有没有办法使用相同的函数名来实现 CRTP 模式?我有一个较长的继承链,其中函数在链的第一级可能没有具体实现,因此必须使用不同的函数名称不是很清晰/可读。
我想要如下内容:
template <typename SecondType>
struct FirstType {
void foo() {
static_cast<SecondType*>(this)->foo();
}
};
template <typename ThirdType>
struct SecondType : FirstType<SecondType> {
void foo() {
static_cast<ThirdType*>(this)->foo();
}
};
struct ThirdType : SecondType<ThirdType> {
void foo() {
// Concrete implementation here
}
};
当然编译器不会提示这个,但我想它会导致隐式 vtable 查找(尽管 virtual
关键字没有出现),违背了使用 CRTP 的目的。
最佳答案
你可以很好地为两个函数使用相同的名称,它会工作得很好。
使用不同名称的好处是,在派生类中未能实现函数将导致编译器错误,而不是在运行时无限递归和可能的堆栈溢出。
关于c++ - 使用具有相同成员函数名称的 CRTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799848/