14th October 2019 / Leave a comment
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
Recent Comments