Skip to content

Instantly share code, notes, and snippets.

@jsrmalvarez
Created April 21, 2024 23:50
Show Gist options
  • Save jsrmalvarez/0cbbc7472ff217d85c5393eb54f8453a to your computer and use it in GitHub Desktop.
Save jsrmalvarez/0cbbc7472ff217d85c5393eb54f8453a to your computer and use it in GitHub Desktop.
Visitor Pattern demo in C++ using std::visit and std::variant
#include <iostream>
#include <variant>
#include <cstdlib>
using Real = double;
struct Rational {
int numerator;
int denominator;
Rational(int numerator, int denominator)
: numerator{numerator}, denominator{denominator} {};
};
using Number = std::variant<Real, Rational>;
struct PrintVisitor
{
void operator()(const Real value) const
{ std::cout << "value: " << value << std::endl; }
void operator()(const Rational rt) const
{ std::cout << "value: " << rt.numerator
<< "/" << rt.denominator << std::endl; }
};
struct SumVisitor
{
Number operator()(Real r1, Real r2) const
{ return r1 + r2; }
Number operator()(Rational rt1, Rational rt2) const
{ return Rational{
rt1.numerator*rt2.denominator + rt2.numerator*rt1.denominator,
rt1.denominator * rt2.denominator }; }
Number operator()(Rational rt, Real r) const
{ return Real{(r*rt.denominator + rt.numerator)/rt.denominator}; }
Number operator()(Real r, Rational rt) const
{ return operator()(rt, r); }
};
int main()
{
const auto _minus_two_thirds = Number{std::in_place_type<Rational>, -2., 3.};
const auto _22_over_15 = Number{std::in_place_type<Rational>, 22., 15.};
const auto _29_point_9 = Number{std::in_place_type<Real>, 29.9};
const auto _11_point_3 = Number{std::in_place_type<Real>, 11.3};
const auto alue = std::visit(SumVisitor{},
_11_point_3,
std::visit(SumVisitor{},
_29_point_9,
std::visit(SumVisitor{},
_22_over_15,
_minus_two_thirds)));
std::visit(PrintVisitor{}, alue);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment