简体   繁体   English

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

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

I am currently messing around with the CRTP pattern using C++ templates. 我目前正在使用C ++模板弄乱CRTP模式。 While fiddling around with visual studio i found several ways/methods in which a derived class can call the base class implementation of a function. 在摆弄Visual Studio的过程中,我发现了派生类可以调用函数的基类实现的几种方式/方法。 Below is the code i am using and also 3 commented out lines showing how call the base class implementation of a function from a derived class. 下面是我正在使用的代码,还有3条注释掉的行,显示了如何从派生类中调用函数的基类实现。 Is there a benefit to using one method over another? 使用一种方法优于另一种方法有好处吗? Are there any differences? 有什么区别吗? What is the most comonly used method? 最常用的方法是什么?

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();
    }
};

The preferred method I've seen is to use this: 我见过的首选方法是使用此方法:

ConsoleApplication::ShowApplicationStartupMsg();

This is nice since it is very clear what you're trying to do, and what parent class the method being called is from (especially useful if you're not the parent class itself is a derived class). 这很不错,因为很清楚您要执行的操作以及被调用的方法来自哪个父类(尤其是如果您不是父类本身是派生类时,则特别有用)。

ConsoleApplication < PortMonitorConsoleApplication >::ShowApplicationStartupMsg();

Use the full name of your base class. 使用基类的全名。

Note that this->ShowApplicationStartupMsg() doesn't call your base, it calls your own function again. 注意,this-> ShowApplicationStartupMsg()不会调用您的基本函数,而是会再次调用您自己的函数。

__super isn't standard (and shouldn't become one, as it's ambiguous with multiple bases). __super不是标准的(并且不应该成为一个,因为它有多个基数是模棱两可的)。

using ConsoleApplication:: is not entirely standard (although I think GCC accepts it) as you don't inherit from ConsoleApplication per se, just one specific instance of it. 使用ConsoleApplication ::并不完全是标准的(尽管我认为GCC接受它),因为您本身不是从ConsoleApplication继承而来,只是它的一个特定实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM