etl::visitor
I'll use the good old familiar 'Shape' example.
First, you create the base for your 'Shape' visitor.
class Square;
class Circle;
class Triangle;
class Shape_Visitor : public etl:visitor<Square, Circle, Triangle>
{
};
Then, you define the Shape base class. It derives from the etl::visitable class that defines a pure virtual accept
function that accepts a Shape_Visitor.
class Shape : public etl::visitable<Shape_Visitor>
{
};
Next, you define the shapes Square, Circle, and Triangle. Each overrides the accept function that calls the visitor with
itself as a parameter.
class Square : public Shape
{
void accept(Shape_Visitor &visitor)
{
visitor.visit(*this);
}
};
class Circle : public Shape
{
void accept(Shape_Visitor &visitor)
{
visitor.visit(*this);
}
};
class Triangle : public Shape
{
void accept(Shape_Visitor &visitor)
{
visitor.visit(*this);
}
};
Now that you have the framework in place, you can do something with it. Here's an example that creates Draw and
Serialise visitors and applies them to a vector of Shape objects.
class Draw_Visitor : public Shape_Visitor
{
public:
void visit(Square &square)
{
std::cout << "Draw the square\n";
}
void visit(Circle &circle)
{
std::cout << "Draw the circle\n";
}
void visit(Triangle &triangle)
{
std::cout << "Draw the triangle\n";
}
};
class Serialise_Visitor : public Shape_Visitor
{
public:
void visit(Square &square)
{
std::cout << "Serialise the square\n";
}
void visit(Circle &circle)
{
std::cout << "Serialise the circle\n";
}
void visit(Triangle &triangle)
{
std::cout << "Serialise the triangle\n";
}
};
Draw_Visitor draw_visitor;
Serialise_Visitor serialise_visitor;
std::vector<Shape*> shape_list;
void Apply(Shape_Visitor &visitor)
{
for (auto pShape : shape_list)
{
pShape->accept(visitor);
}
}
int main()
{
Square square;
Circle circle;
Triangle triangle;
shape_list.push_back(&square);
shape_list.push_back(&circle);
shape_list.push_back(&triangle);
Apply(draw_visitor);
Apply(serialise_visitor);
return 0;
}
The output from the example is as follows.
Draw the square
Draw the circle
Draw the triangle
Serialise the square
Serialise the circle
Serialise the triangle