CRTP - 如何从派生类调用方法的基类实现
CRTP - How to call the base class implemention of a method from the derived class?
我目前正在使用C++模板弄乱CRTP模式。 在摆弄Visual Studio时,我发现了派生类可以调用函数的基类实现的几种方法/方法。 下面是我正在使用的代码,还有 3 个注释掉的行,显示了如何从派生类调用函数的基类实现。 使用一种方法比使用另一种方法有什么好处吗? 有什么区别吗? 最常用的方法是什么?
template<typename T>
struct ConsoleApplication
{
ConsoleApplication()
{
auto that = reinterpret_cast<T*>(this);
that->ShowApplicationStartupMsg();
}
void ShowApplicationStartupMsg()
{
}
};
struct PortMonitorConsoleApplication : ConsoleApplication < PortMonitorConsoleApplication >
{
void ShowApplicationStartupMsg()
{
// __super::ShowApplicationStartupMsg();
// this->ShowApplicationStartupMsg();
// ConsoleApplication::ShowApplicationStartupMsg();
}
};
我见过的首选方法是使用这个:
ConsoleApplication::ShowApplicationStartupMsg();
这很好,因为非常清楚您要做什么,以及被调用的方法来自哪个父类(如果您不是父类本身是派生类,则特别有用)。
ConsoleApplication < PortMonitorConsoleApplication >::ShowApplicationStartupMsg();
使用基类的全名。
请注意,this->ShowApplicationStartupMsg() 不会调用你的基,它会再次调用你自己的函数。
__super不是标准的(也不应该成为一个,因为它在多个碱基上是模棱两可的)。
使用ConsoleApplication::并不完全标准(尽管我认为GCC接受它),因为您本身不是从ConsoleApplication继承的,只是它的一个特定实例。
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用