Templated implementation of the Visitor Pattern for C++11

This is an update to the previous post about templating the Visitor pattern.
Templated implementation of the Visitor Pattern for C++03

I won’t repeat the bulk of the post as the examples will be identical.

The new code uses ‘variadic temples’ that were introduced with C++11, and as such, greatly simplifies the code required.

Visitable

  //*****************************************************************
  /// The visitable class for N types.
  //*****************************************************************
  template <typename T1, typename... Types>
  class visitable : public visitable<T1>, public visitable<Types...>
  {
  public:

    using visitable<T1>::accept;
    using visitable<Types...>::accept;
  };

  //*****************************************************************
  /// The specialised visitable class for 1 type.
    //*****************************************************************
  template <typename T1>
  class visitable<T1>
  {
  public:

    virtual void accept(T1&) = 0;
  };
Visitiable

There, that’s it! It is able to handle any number of visitor types and doesn’t require N specialisations of the template.
The change to Visitor is just as radical.

Visitor

  //*****************************************************************
  /// The visitor class for N types.
  //*****************************************************************
  template <typename T1, typename... Types>
  class visitor : public visitor<T1>, public visitor<Types...>
  {
  public:

    using visitor<T1>::visit;
    using visitor<Types...>::visit;
  };

  //*****************************************************************
  /// The specialised visitor class for 1 type.
  //*****************************************************************
  template <typename T1>
  class visitor<T1>
  {
  public:

    virtual void visit(T1&) = 0;
  };
Visitor
John Wellbelove

John Wellbelove

Director of Aster Consulting Ltd
United Kingdom
I have been involved in technology and computer systems for all of my working life and have amassed considerable knowledge of designing and implementing systems that are both performant and correct. My role normally encompasses the entire project life-cycle, from specification to maintenance phase. Most systems I have worked on have required high speed and deterministic performance, often within a highly constrained platform. I am experienced in designing and adapting algorithms to solutions that are both space and time efficient, avoiding the normal overheads of standard solutions. Acting as a mentor for colleagues has often been a significant, though unofficial, part of my role.

I administer an open source project on Github.
See http://www.etlcpp.com/

Leave a Reply

Your email address will not be published. Required fields are marked *