call sub class method from base class specific function

回眸只為那壹抹淺笑 提交于 2019-12-23 04:22:44

问题


I've got a question concerning handling of virtual function in C++ programming. I have something like this:

template<class T>
class baseClass
{
    virtual void doSomething(T& t) {
        // some baseClass specific code
    }

    void doSomethingElse(T& t) {
        // some baseClass specific code

        this->doSomething(t);
    }
}

template<class T>
class subClass
{
    virtual void doSomething(T&) {
        // some subclass related code
    }
}

Now, if I construct an object of type subClass....

int main(int argc, char *argv[])
{
    subClass<anyType> * subClassObject = new subClass<anyType>();
    subClassObject->doSomethingElse(anyTypeObject);
}

.... and call the doSomethingElse method of the base class, this method will call the doSomething method of the base class and not of the sub class.

What I want to have, is calling the doSomething method of the subclass (not of the baseClass).

Can anybody tell me how to accomplish that?


回答1:


You could accomplish it with CRTP:

template<class T, class Derived>
class baseClass
{    
    void doSomethingElse(T& t) {
        // some baseClass specific code
        static_cast<Derived*>(this)->doSomething(t);
    }
}

template<class T>
class subClass : public baseClass<T, subClass>
{
    void doSomething(T&) {
        // some subclass related code
    }
}

See this for discussion about virtual template methods




回答2:


I made several changes to your code to get it to compile, and with g++ 4.5 it indicates the subclass method is being called. Here's the code I compiled:

#include <iostream>

template<class T>
class baseClass
{
public:
    virtual void doSomething(T& t) {
        std::cout << "Base" << std::endl;
        // some baseClass specific code
    }

    void doSomethingElse(T& t) {
        // some baseClass specific code

        this->doSomething(t);
    }
};

template<class T>
class subClass : public baseClass<T>
{
    virtual void doSomething(T&) {
        std::cout << "Child" << std::endl;
        // some subclass related code
    }
};

int main()
{
    typedef int anyType;

    subClass<anyType> * subClassObject = new subClass<anyType>();
    int foo;
    subClassObject->doSomethingElse(foo);
}


来源:https://stackoverflow.com/questions/11848800/call-sub-class-method-from-base-class-specific-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!