使用具有相同成员函数名称的 CRTP
Using CRTP with same member function name
当我看到使用的 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 的目的。
您可以很好地对两个函数使用相同的名称,它将正常工作。
使用不同名称的优点是,未能在派生类中实现函数将导致编译器错误,而不是在运行时无限递归和可能的堆栈溢出。
为什么不断言成员函数不同?从 ThirdType 中删除 foo() 会给你一个编译错误,并显示一条很好的消息。
#include <type_traits>
template <typename SecondType>
struct FirstType {
void foo() {
static_assert(
!std::is_same<
decltype(&FirstType::foo),
decltype(&SecondType::foo)
>::value,
"SecondType must implement method 'void foo()'");
static_cast<SecondType*>(this)->foo();
}
};
template <typename ThirdType>
struct SecondType : FirstType<SecondType<ThirdType>> {
void foo() {
static_assert(
!std::is_same<
decltype(&SecondType::foo),
decltype(&ThirdType::foo)
>::value,
"ThirdType must implement method 'void foo()'");
static_cast<ThirdType*>(this)->foo();
}
};
struct ThirdType : SecondType<ThirdType> {
void foo() {
// Concrete implementation here
}
};
template class SecondType<ThirdType>;
template class FirstType<SecondType<ThirdType>>;
相关文章:
- 将具有固定签名的自定义函数名称注入 CRTP
- 检测使用 CRTP 的类中的成员函数
- 如何断言 CRTP 的函数为最终函数?
- 使用CRTP将基类的子类传递给构造函数
- 如何在 CRTP 中实现析构函数?
- 仅函数的多重继承 - 没有虚拟和 CRTP
- C++使用 CRTP 模板模板基类中的构造函数
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- 解决 CRTP 函数重载歧义问题
- CRTP 在父级析构函数中调用子函数
- 为什么在此 CRTP 基函数调用中添加引用会消除错误?
- 我可以将CRTP与虚拟函数或函数一起使用,以供访问者算法更改的访问者算法
- CRTP 和复制/移动赋值/构造函数继承
- 如何在 CRTP 中调用派生的模板化函数
- 在执行 SFINAE 时访问模板派生类 (CRTP) 的静态函数时类型不完整
- 为什么CRTP(奇怪的递归模板模式)试图选择另一个私有基类的另一个同名函数
- 另一个命名空间和 CRTP 中的模板友元函数
- 使用CRTP时,如何调用派生类的构造函数
- 使用派生的模板参数类型作为函数 (CRTP) 的返回类型
- 使用具有相同成员函数名称的 CRTP