Skip to content

Instantly share code, notes, and snippets.

@marcoemorais
Created October 20, 2023 05:06
Show Gist options
  • Save marcoemorais/4fc77d35fa0ad4f599d381e1bda693fd to your computer and use it in GitHub Desktop.
Save marcoemorais/4fc77d35fa0ad4f599d381e1bda693fd to your computer and use it in GitHub Desktop.
Object oriented (OO) implementation of the Visitor pattern.
#include <variant>
#include <vector>
using namespace std;
class Circle;
class Square;
class DrawVisitor {
public:
void operator()(const Circle&) const { cout << "draw circle\n"; }
void operator()(const Square&) const { cout << "draw square\n"; }
};
class Circle {
public:
explicit Circle(double radius) : radius_(radius) {}
private:
double radius_;
};
class Square {
public:
explicit Square(double side) : side_(side) {}
private:
double side_;
};
int main()
{
using Shape = variant<Circle, Square>;
using Shapes = vector<Shape>;
Shapes shapes;
shapes.emplace_back(Circle{1.0});
shapes.emplace_back(Square{1.0});
for (const auto& shape : shapes) {
std::visit(DrawVisitor{}, shape);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment