[2026] C++ Visitor Pattern Explained | Double Dispatch, std::variant & std::visit

[2026] C++ Visitor Pattern Explained | Double Dispatch, std::variant & std::visit

이 글의 핵심

Visitor pattern in modern C++: classic accept/visit vs std::variant + std::visit (C++17), ASTs, trade-offs when adding types vs operations—tutorial for English readers.

Visitor sits with other behavioral patterns in C++ behavioral patterns #20-1 and the overview #20-2.

What is Visitor Pattern?

double dispatch pattern 다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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)

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

#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

다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

// 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

아래 코드는 cpp를 사용한 구현 예제입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 코드를 직접 실행해보면서 동작을 확인해보세요.

// 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

아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 코드를 직접 실행해보면서 동작을 확인해보세요.

// ✅ 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

아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

// 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

아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

// 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.

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.

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3