Run Code  | API  | Code Wall  | Misc  | Feedback  | Login  | Theme  | Privacy  | Patreon 

How to get base class

#include <iostream>
#include <type_traits>

template<typename T>
T& getParentObject( int (T::*)() const );

struct BaseC
{
    //If I uncomment the line below, I get a compilation error ~~~~~~~~~~~~~~~~~~~~~~
    //using Base  = std::remove_reference<decltype(getParentObject(&BaseC::type))>::type;
    
    virtual int type() const { return 0; }
};

struct Derived : BaseC
{
    using Base  = std::remove_reference<decltype(getParentObject(&Derived::type))>::type;
    
    int type() const { return 1; }
};

struct DDerived : Derived
{
    using Base  = std::remove_reference<decltype(getParentObject(&DDerived::type))>::type;
    
    int type() const { return 2; }
};

template<typename T>
struct Logger 
{
    static void Print()
    {
        std::cout << "Base Logger" << std::endl;
    }
};

template<>
struct Logger<Derived>
{
    static void Print()
    {
        std::cout << "Derived Logger" << std::endl;
    }
};

template<>
struct Logger<DDerived>
{
    static void Print()
    {
        std::cout << "DDerived Logger" << std::endl;
    }
};

    
int main()
{
    Logger<Derived::Base>::Print();   
    Logger<DDerived::Base>::Print();  
}
 run  | edit  | history  | help 0