I found one mechanism, where at least we are prompted to announce the overridden method explicitly. It's not the perfect way though.
Suppose, we have few pure virtual
methods in the base class B
:
class B {
virtual void foo () = 0;
virtual void bar (int) = 0;
};
Among them, suppose we want only foo()
to be overridden by the whole hierarchy. For simplicity, we have to have a virtual
base class, which contains that particular method. It has a template constructor, which just accepts the type same as that method.
class Register_foo {
virtual void foo () = 0; // declare here
template<typename T> // this matches the signature of 'foo'
Register_foo (void (T::*)()) {}
};
class B : public virtual Register_foo { // <---- virtual inheritance
virtual void bar (int) = 0;
Base () : Register_foo(&Base::foo) {} // <--- explicitly pass the function name
};
Every subsequent child class in the hierarchy would have to register a foo
inside its every constructor explicitly. e.g.:
struct D : B {
D () : Register_foo(&D::foo) {}
virtual void foo () {};
};
This registration mechanism has nothing to do with the business logic. Though, the child class
can choose to register using its own foo
or its parent's foo
or even some similar syntax method, but at least that is announced explicitly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…