简体   繁体   中英

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. 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. 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. 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.

__super isn't standard (and shouldn't become one, as it's ambiguous with multiple bases).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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