C++ Visitor Pattern Explained | Double Dispatch, std::variant & std::visit
이 글의 핵심
Visitor pattern and double dispatch in C++, plus value-based alternatives with std::variant and std::visit for closed type sets.
Visitor sits with other behavioral patterns in C++ behavioral patterns #20-1 and the overview #20-2.
What is Visitor Pattern?
double dispatch pattern
#include <iostream>
// forward declaration
class Circle;
class Rectangle;
// Visitor
class ShapeVisitor {
public:
virtual void visit(Circle& c) = 0;
virtual void visit(Rectangle& r) = 0;
virtual ~ShapeVisitor() = default;
};
// Shape
class Shape {
public:
virtual void accept(ShapeVisitor& v) = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
void accept(ShapeVisitor& v) override { v.visit(*this); }
double getRadius() const { return radius; }
private:
double radius;
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
void accept(ShapeVisitor& v) override { v.visit(*this); }
double getWidth() const { return width; }
double getHeight() const { return height; }
private:
double width, height;
};
// specific Visitor
class AreaCalculator : public ShapeVisitor {
public:
void visit(Circle& c) override {
area = 3.14159 * c.getRadius() * c.getRadius();
}
void visit(Rectangle& r) override {
area = r.getWidth() * r.getHeight();
}
double getArea() const { return area; }
private:
double area = 0;
};
int main() {
Circle c(5.0);
Rectangle r(4.0, 6.0);
AreaCalculator calc;
c.accept(calc);
std::cout << "Circle area: " << calc.getArea() << '\n';
r.accept(calc);
std::cout << "Rectangle area: " << calc.getArea() << '\n';
}
std::variant + std::visit (C++17)
#include <variant>
#include <iostream>
struct Circle {
double radius;
};
struct Rectangle {
double width, height;
};
using Shape = std::variant<Circle, Rectangle>;
// Visitor (function object)
struct AreaCalculator {
double operator()(const Circle& c) const {
return 3.14159 * c.radius * c.radius;
}
double operator()(const Rectangle& r) const {
return r.width * r.height;
}
};
int main() {
Shape s1 = Circle{5.0};
Shape s2 = Rectangle{4.0, 6.0};
double area1 = std::visit(AreaCalculator{}, s1);
double area2 = std::visit(AreaCalculator{}, s2);
std::cout << "Circle: " << area1 << '\n';
std::cout << "Rectangle: " << area2 << '\n';
}
Practical example
Example 1: Multiple Visitors
#include <variant>
#include <iostream>
#include <string>
struct Circle { double radius; };
struct Rectangle { double width, height; };
struct Triangle { double base, height; };
using Shape = std::variant<Circle, Rectangle, Triangle>;
// area
struct AreaVisitor {
double operator()(const Circle& c) const {
return 3.14159 * c.radius * c.radius;
}
double operator()(const Rectangle& r) const {
return r.width * r.height;
}
double operator()(const Triangle& t) const {
return 0.5 * t.base * t.height;
}
};
// output
struct PrintVisitor {
void operator()(const Circle& c) const {
std::cout << "Circle(r=" << c.radius << ")\n";
}
void operator()(const Rectangle& r) const {
std::cout << "Rectangle(w=" << r.width << ", h=" << r.height << ")\n";
}
void operator()(const Triangle& t) const {
std::cout << "Triangle(b=" << t.base << ", h=" << t.height << ")\n";
}
};
int main() {
Shape s = Circle{5.0};
double area = std::visit(AreaVisitor{}, s);
std::cout << "Area: " << area << '\n';
std::visit(PrintVisitor{}, s);
}
Example 2: Lambda Visitor
#include <variant>
#include <iostream>
// overloaded helper
template<typename... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};
template<typename... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
struct Circle { double radius; };
struct Rectangle { double width, height; };
using Shape = std::variant<Circle, Rectangle>;
int main() {
Shape s = Circle{5.0};
std::visit(overloaded{
{
std::cout << "Circle: " << c.radius << '\n';
},
{
std::cout << "Rectangle: " << r.width << "x" << r.height << '\n';
}
}, s);
}
Example 3: State change
#include <variant>
#include <iostream>
struct Idle {};
struct Running { int progress; };
struct Completed { int result; };
using State = std::variant<Idle, Running, Completed>;
struct StateHandler {
void operator()(Idle&) {
std::cout << "State: Idle\n";
}
void operator()(Running& r) {
std::cout << "State: Running (" << r.progress << "%)\n";
r.progress += 10;
}
void operator()(Completed& c) {
std::cout << "State: Completed (result=" << c.result << ")\n";
}
};
int main() {
State state = Running{50};
std::visit(StateHandler{}, state);
std::visit(StateHandler{}, state);
}
Example 4: AST Traversal
#include <variant>
#include <memory>
#include <iostream>
struct Number {
int value;
};
struct BinaryOp {
char op;
std::unique_ptr<struct Expr> left;
std::unique_ptr<struct Expr> right;
};
using ExprVariant = std::variant<Number, BinaryOp>;
struct Expr {
ExprVariant data;
};
struct Evaluator {
int operator()(const Number& n) const {
return n.value;
}
int operator()(const BinaryOp& op) const {
int l = std::visit(*this, op.left->data);
int r = std::visit(*this, op.right->data);
switch (op.op) {
case '+': return l + r;
case '-': return l - r;
case '*': return l * r;
case '/': return l / r;
default: return 0;
}
}
};
Traditional vs Modern
// traditional (virtual function)
class Visitor {
virtual void visit(TypeA&) = 0;
virtual void visit(TypeB&) = 0;
};
class Shape {
virtual void accept(Visitor&) = 0;
};
// Modern (variant + visit)
using Shape = std::variant<TypeA, TypeB>;
struct Visitor {
void operator()(TypeA&) { /* ... */ }
void operator()(TypeB&) { /* ... */ }
};
std::visit(Visitor{}, shape);
Frequently occurring problems
Problem 1: Adding types
// Tradition: Fix all Visitors
class Visitor {
virtual void visit(Circle&) = 0;
virtual void visit(Rectangle&) = 0;
// Modify all Visitors when adding a Triangle
};
// Modern: Modify only variant
using Shape = std::variant<Circle, Rectangle, Triangle>;
Issue 2: Return value
// ✅ Return value
struct AreaVisitor {
double operator()(const Circle& c) const {
return 3.14159 * c.radius * c.radius;
}
};
double area = std::visit(AreaVisitor{}, shape);
Issue 3: Status
// Status on Visitor
struct Counter {
int count = 0;
void operator()(const Circle&) { ++count; }
void operator()(const Rectangle&) { ++count; }
};
Counter counter;
for (const auto& shape : shapes) {
std::visit(counter, shape);
}
Problem 4: Circular dependencies
// forward declaration + unique_ptr
struct Expr;
struct BinaryOp {
std::unique_ptr<Expr> left;
std::unique_ptr<Expr> right;
};
struct Expr {
std::variant<Number, BinaryOp> data;
};
When to use
- Traditional Visitor: type fixed, polymorphism required
- std::variant + std::visit: type-restricted, performance-critical, modern C++
FAQ
Q1: Visitor Pattern?
A: Double dispatch pattern.
Q2: Purpose?
A: Processing by type.
Q3: std::visit?
A: Visit C++17 variant.
Q4: Advantages?
A: Type safety, extensibility.
Q5: Disadvantages?
A: Requires modification when adding type.
Q6: What are the learning resources?
A:
- “Design Patterns”
- “C++17 STL”
- cppreference.com
Good article to read together (internal link)
Here’s another article related to this topic.
- Complete Guide to C++ Strategy Pattern | Algorithm encapsulation and runtime replacement
- C++ Factory Pattern Complete Guide | Object creation encapsulation and extensibility
- C++ CRTP Complete Guide | Static polymorphism and compile-time optimization
Practical tips
These are tips that can be applied right away in practice.
Debugging tips
- If you run into a problem, check the compiler warnings first.
- Reproduce the problem with a simple test case
Performance Tips
- Don’t optimize without profiling
- Set measurable indicators first
Code review tips
- Check in advance for areas that are frequently pointed out in code reviews.
- Follow your team’s coding conventions
Practical checklist
This is what you need to check when applying this concept in practice.
Before writing code
- Is this technique the best way to solve the current problem?
- Can team members understand and maintain this code?
- Does it meet the performance requirements?
Writing code
- Have you resolved all compiler warnings?
- Have you considered edge cases?
- Is error handling appropriate?
When reviewing code
- Is the intent of the code clear?
- Are there enough test cases?
- Is it documented?
Use this checklist to reduce mistakes and improve code quality.
Keywords covered in this article (related search terms)
This article will be helpful if you search for C++, visitor, pattern, variant, polymorphism, etc.
Related articles
- C++ CRTP Complete Guide | Static polymorphism and compile-time optimization
- C++ Factory Pattern Complete Guide | Object creation encapsulation and extensibility
- Complete Guide to C++ Strategy Pattern | Algorithm encapsulation and runtime replacement
- C++ Adapter Pattern Complete Guide | Interface conversion and compatibility
- Complete Guide to C++ Command Pattern | Undo and macro system