CRTP - 如何从派生类调用方法的基类实现

CRTP - How to call the base class implemention of a method from the derived class?

本文关键字:方法 调用 基类 实现 派生 CRTP      更新时间:2023-10-16

我目前正在使用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继承的,只是它的一个特定实例。