源自范围调用函数(Calling function from derived scope)

2019-11-02 05:42发布

我有一些代码,这似乎similair这样:

#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;
}

现在,这个输出ofcourse Base::test()但我希望它输出Derived::test() 利用虚拟函数调用并使用调用的函数重载一个不同的符号: Derived::test

是否有人知道这是可能实现的?

Answer 1:

您可以使用所谓的奇异递归式模式(CRTP),使Base模板

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

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

然后,你就中派生DerivedBase<Derived> ,而不是仅仅Base

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

这是一个活生生的例子



文章来源: Calling function from derived scope