C ++ avoids code duplication for constant and non-constant visits

I have a class that should call the visitor method for each member variable. Something like that:

class A{ int a, b, c; public: void accept(Visitor &visitor){ visitor.visit(a); visitor.visit(b); visitor.visit(c); } }; 

How can I get the void accept() const method with the same code without duplicating the code?

The obvious duplication solution is to add a method:

 void accept(Visitor &visitor) const { visitor.visit(a); visitor.visit(b); visitor.visit(c); } 

This method has exactly the meaning that I want, but I would like to avoid code duplication. The reason to have both methods is the ability to read variables by the visitor of the β€œread” and to have the accept method beautifully const . Then the non-constant accept can be used to "record / update" visitors.

+7
source share
2 answers

You can create a helper function of a static class template that will output a constant based on the type of the this pointer that you provide to it. Like this:

 class A{ int a, b, c; public: void accept(Visitor &visitor){ acceptImpl(*this, visitor); } void accept(Visitor &visitor) const{ acceptImpl(*this, visitor); } private: template<typename t_A> static void acceptImpl(t_A& aObj, Visitor &visitor) { visitor.visit(aObj.a); visitor.visit(aObj.b); visitor.visit(aObj.c); } }; 
+12
source

Template Helper:

 class A{ int a, b, c; private: template <typename T> static void do_visiting(T &self, Visitor &visitor) { visitor.visit(self.a); visitor.visit(self.b); visitor.visit(self.c); } public: void accept(Visitor &visitor) { do_visiting(*this, visitor); // calls do_visiting<A> } void accept(Visitor &visitor) const { do_visiting(*this, visitor); // calls do_visiting<const A> } }; 
+2
source

All Articles