问题
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