Calling function from derived scope

孤街浪徒 提交于 2019-12-12 05:16:38

问题


I have some code which seems similair to this:

#include <iostream>

class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl; 
    }

    void test2() {
        test();
    }
};

class Derived : public Base {
public:
    void test() {
        std::cout << "Derived::test()" << std::endl;
    }
};

int main() {
    Derived d;
    d.test2();
    return 0;
}

Now this outputs ofcourse Base::test(), however I want it to output Derived::test() without making use of virtual function calls and using an different notation for the function overload called: Derived::test.

Does someone know if this is possible to achieve?


回答1:


You could use the so-called Curiously Recurring Type Pattern (CRTP) and make Base a class template:

template<typename D>
class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl;
    }

    void test2() {
        (static_cast<D*>(this))->test();
    }
};

Then, you would derive Derived from Base<Derived> instead of just Base:

class Derived : public Base<Derived> {
//                     ^^^^^^^^^^^^^
//                     This is the only change required in Derived
public:
    void test() {
        std::cout << "Derived::test()" << std::endl;
    }
};

Here is a live example.



来源:https://stackoverflow.com/questions/17325176/calling-function-from-derived-scope

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