Visitor and templated virtual methods

Posted by Thomas Matthews on Stack Overflow See other posts from Stack Overflow or by Thomas Matthews
Published on 2010-05-21T23:16:16Z Indexed on 2010/05/21 23:20 UTC
Read the original article Hit count: 479

In a typical implementation of the Visitor pattern, the class must account for all variations (descendants) of the base class. There are many instances where the same method content in the visitor is applied to the different methods. A templated virtual method would be ideal in this case, but for now, this is not allowed.

So, can templated methods be used to resolve virtual methods of the parent class?

Given (the foundation):

struct Visitor_Base; // Forward declaration.

struct Base
{
  virtual accept_visitor(Visitor_Base& visitor) = 0;
};

// More forward declarations
struct Base_Int;
struct Base_Long;
struct Base_Short;
struct Base_UInt;
struct Base_ULong;
struct Base_UShort;

struct Visitor_Base
{
  virtual void operator()(Base_Int& b) = 0;
  virtual void operator()(Base_Long& b) = 0;
  virtual void operator()(Base_Short& b) = 0;
  virtual void operator()(Base_UInt& b) = 0;
  virtual void operator()(Base_ULong& b) = 0;
  virtual void operator()(Base_UShort& b) = 0;
};

struct Base_Int : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

struct Base_Long : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

struct Base_Short : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

struct Base_UInt : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

struct Base_ULong : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

struct Base_UShort : public Base
{
  void accept_visitor(Visitor_Base& visitor)
  {
     visitor(*this);
  }
};

Now that the foundation is laid, here is where the kicker comes in (templated methods):

struct Visitor_Cout : public Visitor
{
  template <class Receiver>
  void operator() (Receiver& r)
  {
     std::cout << "Visitor_Cout method not implemented.\n";
  }
};

Intentionally, Visitor_Cout does not contain the keyword virtual in the method declaration. All the other attributes of the method signatures match the parent declaration (or perhaps specification).

In the big picture, this design allows developers to implement common visitation functionality that differs only by the type of the target object (the object receiving the visit). The implementation above is my suggestion for alerts when the derived visitor implementation hasn't implement an optional method.

Is this legal by the C++ specification?

(I don't trust when some says that it works with compiler XXX. This is a question against the general language.)

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates