问题
Is there a way (templates, macros anything else) to substitute a call to hidden_in_derived from common method at compile time, so that instance of Derived calls it's own hidden_in_derived (without making hidden_in_derived virtual in Base) ?
#include <iostream>
class Base {
public:
void common() {
// some calls to other methods
hidden_in_derived();
// yet some calls to other methods
}
void hidden_in_derived() {
std::cout << "A" << std::endl;
}
};
class Derived : public Base {
public:
void hidden_in_derived() {
std::cout << "B" << std::endl;
}
};
int main() {
Derived d;
d.common(); // want hidden_in_derived (prints "B") here somehow ?
}
回答1:
Make it virtual, then you can even use Base class ptr: https://wandbox.org/permlink/tF5Cb4fE5jEhG5Ru
Or just like you did with an object: https://wandbox.org/permlink/W2EJGXwioXjqd1Zx
来源:https://stackoverflow.com/questions/59087461/call-hidden-non-virtual-method-of-derived-class-from-base