Is there a way to use the
template
mechanism to merge the two (such as supply 'const' as a parameter to the template)?
You can supply it through a template template parameter, and also keep the pure visitor implementation generic. I originally did this in C++11, but since you say you don't have it, I'll present one with type lists instead.
Here is the type list implementation.
/* Our empty node for our type list. */
class Empty {};
/* Cons for our type list. */
template <typename First_, typename Rest_>
class Cons {
public:
/* First type */
typedef First_ First;
/* Rest. */
typedef Rest_ Rest;
}; // Cons<First_, Rest_>
Here is the generic visitor implementation.
/* Forward declaration. */
template <template <typename> class Decorator, typename Members>
class VisitorRecur;
/* Base case. */
template <template <typename> class Decorator, typename Member>
class VisitorRecur<Decorator, Cons<Member, Empty> > {
public:
/* Pure virtual for each of the members. */
virtual void operator()(
typename Decorator<Member>::Type that) const = 0;
}; // VisitorRecur<Decorator, Member>
/* Recursive case. */
template <template <typename> class Decorator, typename Members>
class VisitorRecur
: public VisitorRecur<Decorator, typename Members::Rest> {
public:
/* Bring the operator()s into scope. */
using VisitorRecur<Decorator, typename Members::Rest>::operator();
/* Pure virtual for each of the members. */
virtual void operator()(
typename Decorator<typename Members::First>::Type that) const = 0;
}; // VisitorRecur<Decorator, typename Members::Rest>
/* Final visitor. */
template <template <typename> class Decorator, typename Members>
class Visitor : public VisitorRecur<Decorator, Members> {
public:
/* Bring the operator()s into scope. */
using VisitorRecur<Decorator, Members>::operator();
}; // Visitor<Decorator, Members>
Here are the two decorators that we'll define.
/* ConstRef. */
template <typename T>
class ConstRef {
public:
typedef const T & Type;
}; // ConstRef<T>
/* Ref. */
template <typename T>
class Ref {
public:
typedef T & Type;
}; // Ref<T>
Here is the use case for it.
/* Forward declarations. */
class Circle;
class Square;
class Triangle;
/* Add the members into a type list. */
typedef Cons<Circle, Cons<Square, Cons<Triangle, Empty> > > Members;
/* Our const visitor which accepts the members by const-ref. */
typedef Visitor<ConstRef, Members> ConstVisitor;
/* Our mutating visitor which accepts the members by ref. */
typedef Visitor<Ref, Members> MutatingVisitor;