C++: Avoiding dual maintenance in inheritance hierarchies
When creating a C++ inheritance structure, you have to define member functions exactly the same in multiple places:
If B is an abstract base class, and D, E, and F all inherit from B, you开发者_运维百科 might have this:
class B
{
virtual func A( ... params ) = 0;
};
class D : public B
{
func A( ... params );
};
/* ... etc... similar implementations for E and F */
So, there is obviously some duplication here. If the interface to B is large, you may have many places to change if the interface needs to change.
A coworker suggested some trickery with an embedded craftily-created #includes, ala:
class D: public B
{
#include "B_Interface.h" // B_Interface.h is a specially crafted .h file
}
This seems a little kludgy? Is it? Is there a better solution to avoid dual maintenance?
Also, maybe the solution here is really better tools to support the language, like Visual Assist X?
Edit: Assume the derived classes must have unique implementations.
Actually, the biggest problem with changing an interface usually is all the code that uses it, not the code that implements it. If it's easy to change it for the implementer, it would probably make life harder for the users.
That it's painful to change a widely used interface is not a bug; it's a feature.
Also, maybe the solution here is really better tools to support the language, like Visual Assist X?
Exactly. Changing method signatures is a key feature of refactoring tools.
If you have to implement them over and over with some default behavior then maybe they should just be virtual, and not pure virtual.
Instead of using the preprocessor for yet another way it should not be used I'd try my editor (or IDE, if that's what you fancy.)
精彩评论