0

Since template functions cannot be virtual. Does anyone know how I would have Base::funcB() call *::funcA() depending on which class the object is from? See the third last line below.

class Base {
public:
    template<typename T>
    void funcA(const T& t){
        std::cout<< "In Base with T = " << t << std::endl;
    }
    
    template<typename T> 
    void funcB(const T& t){            
        funcA(t);
    }
};

class Derived: public Base {
public:
    template<typename T>
    void funcA(const T& t){
        std::cout<< "In Derived with T = " << t << std::endl;
    }
};


int main()
{
    std::cout<<"Direct function override\n";
    Base().funcA("ABC");    // Output: In Base with T = ABC
    Derived().funcA("ABC"); // Output: In Derived with T = ABC
    
    std::cout<<"\n\n";
    std::cout<<"Indirect function invocation\n";
    Base().funcB("ABC");    // Output: In Base with T = ABC
    Derived().funcB("ABC"); // Output: In Base with T = ABC       !!!BAD!!! I want Derived, not Based
    return 0;
}

https://onlinegdb.com/Uea1VH9Rj

xkrz
  • 166
  • 9

0 Answers0