It is possible that you are looking for the Visitor template here. If you have an object that you describe with several non-trivial member fields, and you find that you have several different functions that completely intersect this data structure in the same way, a visitor pattern can be very useful in reducing the amount of code duplication . This is not automatic, through, you should write functions that intersect all the fields of the participant, but you need to do this only once, and you can use it many times with different classes of visitors who do different things.
The visitor template includes enough code to write, you need an abstract base class for visitors:
class VisitorBase { virtual void enter(Example& e)=0; virtual void leave(Example& e)=0; virtual void enter(AnotherClass& e)=0; virtual void leave(AnotherClass& e)=0; etc ... };
Then you need to accept functions in all classes that will be visited:
void Example::accept( VisitorBase& visitor ) { visitor.enter(*this); member1.accept(visitor); member2.accept(visitor); member3.accept(visitor); visitor.leave(*this); }
And finally, you need to implement specific classes of visitors that perform the work you are interested in, which usually comes down to collecting information from the data structure, making changes to the data structure, or combinations thereof. Google Visitor and you will find a lot of help about this.
Rasmus storjohann
source share