Defining Visitors - GerdHirsch/Cpp-VisitorFrameworkCyclicAcyclic GitHub Wiki
To define a Visitor you
can either use visits<typelist>
to inherit from or specify a list of types visits<E1, E2, NonVisitable>
with the types you want to visit. The list must be a subset of the types of your Repository
other types can not be visited.
#include "MyRepository.h"
class DemoVisitor : public Repository::visits<typelist>{
//class DemoVisitor : public Repository::visits<E1, NonVisitable>{
public:
std::string toString() const override { return "DemoVisitor"; }
void visit(E1& v) {
std::cout << toString() << "::visit(" << v.toString() << ")" << std::endl;
}
void visit(NonVisitable& v) {
std::cout << toString() << "::visit(" << v.toString() << ")" << std::endl;
}
//void visit(E2& v) {
// std::cout << toString() << "::visit(" << v.toString() << ")" << std::endl;
//}
};
Constraints to Visitors: it´s not allowed to store Visitables out of the scope of the corresponding visit method. Using Visitable v outside is undefined behaviour, the references may dangle.
If you use an acyclic Visitor, your Visitor inherits only the VisitorInterfaces of the specified types in the list
of Repository::visits<...>
.
If you use an cyclic Visitor, the types in the list are just ignored, cause cyclic visitors have a common base class, with a visit method for each element to be visited, either abstract or with a default implementation.
If you specify BaseKind::Default
in the
Repository
,
you don't have to provide a visit(..)
method for
all Types in the typelist
, but only for Types you realy want to visit. The Framework provides a default visit(..)
method that uses the specified
DefaultPolicy
.
see also: SwitchCyclicAcyclicVisitors.h