Created
October 20, 2023 05:06
-
-
Save marcoemorais/4fc77d35fa0ad4f599d381e1bda693fd to your computer and use it in GitHub Desktop.
Object oriented (OO) implementation of the Visitor pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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