Skip to content

双重分派 (Double Dispatch)

什么是双重分派?

双重分派是一种技巧:它让同一个运算同时依赖两个对象的运行时类型。C++ 的虚函数调用只能按一个对象的运行时类型分派,也就是你调用它的那一个对象。双重分派把这次选择做了两遍:先看第一个操作数,再看第二个操作数。

核心思想:把第二个操作数的运行时类型变成一个编译期就能选中的重载——办法是让第一个操作数把运算转交给第二个操作数。

为什么需要双重分派?

问题场景

假设你要写一局石头剪刀布。胜负取决于两个出拳的运行时类型:

// Problem: the outcome depends on the types of both moves, but a virtual
// call can only dispatch on one of them.
std::string whoWins(Move& a, Move& b) {
    if (typeid(a) == typeid(Rock)) {
        if (typeid(b) == typeid(Paper)) {
            return "Paper beats Rock";
        }
        if (typeid(b) == typeid(Scissors)) {
            return "Rock beats Scissors";
        }
        return "a draw";
    }
    // ... the same nesting for Paper and Scissors
}

问题:

  1. 嵌套的层数随出拳种类增长——三种出拳就要九个分支
  2. 运行时类型是当标签比较的,编译器没法帮你检查
  3. 每增加一种出拳,都得改一遍所有分支

解决方案

让访问者带着运算,然后分派两次——先按第一个出拳的类型分派,再按第二个出拳的类型分派:

// The visitor interface: one overload per move type.
class Visitor {
public:
    virtual ~Visitor() = default;
    virtual void visit(Rock& rock) = 0;
    virtual void visit(Paper& paper) = 0;
    virtual void visit(Scissors& scissors) = 0;
};

// The move interface: accept() hands the visitor a reference of our own
// type. That is the first half of the double dispatch.
class Element {
public:
    virtual ~Element() = default;
    virtual void accept(Visitor& visitor) = 0;
    virtual std::string name() const = 0;
};

// The first dispatch lands in the overload of the first move. Inside it the
// second dispatch asks the opponent to accept a visitor that already knows
// our type, so the operation finally sees both types.
class MatchVisitor : public Visitor {
public:
    explicit MatchVisitor(Element& opponent) : opponent_(opponent) {}

    void visit(Rock& rock) override {
        OpponentVisitor<Rock> visitor(rock);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    void visit(Paper& paper) override {
        OpponentVisitor<Paper> visitor(paper);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    void visit(Scissors& scissors) override {
        OpponentVisitor<Scissors> visitor(scissors);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    const std::string& result() const { return result_; }

private:
    Element& opponent_;
    std::string result_;
};

优点:

  1. 运算集中在一处,而不是散落在各个出拳类里
  2. 算结果的地方,两个运行时类型都已知
  3. 新增一个运算就是新增一个访问者,而不是去改各个出拳类

模式结构

                   ┌────────────────────────┐
                   │        Visitor         │
                   │  one overload per type │
                   └───────────┬────────────┘
                               │
                   ┌───────────▼────────────┐
                   │      MatchVisitor      │  ← first dispatch
                   │   (holds the opponent) │
                   └───────────┬────────────┘
                               │  opponent_.accept(...)
                   ┌───────────▼────────────┐
                   │ OpponentVisitor<First> │  ← second dispatch
                   └───────────┬────────────┘
                               │
          ┌────────────────────┼────────────────────┐
          │                    │                    │
   ┌──────▼──────┐      ┌──────▼──────┐      ┌──────▼──────┐
   │    Rock     │      │    Paper    │      │   Scissors  │
   └─────────────┘      └─────────────┘      └─────────────┘
                   ← the visited classes

代码实现

1. 定义元素接口与访问者接口

#include <iostream>
#include <string>

// Forward declarations: the visitor names every move type.
class Rock;
class Paper;
class Scissors;

// The visitor interface: one overload per move type. The overload is
// chosen by the runtime type of the argument.
class Visitor {
public:
    virtual ~Visitor() = default;
    virtual void visit(Rock& rock) = 0;
    virtual void visit(Paper& paper) = 0;
    virtual void visit(Scissors& scissors) = 0;
};

// The move interface: accept() hands the visitor a reference of our own
// type, which is the first half of the double dispatch.
class Element {
public:
    virtual ~Element() = default;
    virtual void accept(Visitor& visitor) = 0;
    virtual std::string name() const = 0;
};

2. 实现具体棋子

class Rock : public Element {
public:
    void accept(Visitor& visitor) override { visitor.visit(*this); }
    std::string name() const override { return "Rock"; }
};

class Paper : public Element {
public:
    void accept(Visitor& visitor) override { visitor.visit(*this); }
    std::string name() const override { return "Paper"; }
};

class Scissors : public Element {
public:
    void accept(Visitor& visitor) override { visitor.visit(*this); }
    std::string name() const override { return "Scissors"; }
};

3. 把运算写成重载集合

// The operation: who wins a round. The overloads are picked by the two
// static types, which the double dispatch has already narrowed down.
std::string outcome(const Rock&, const Rock&) { return "a draw"; }
std::string outcome(const Rock&, const Paper&) { return "Paper beats Rock"; }
std::string outcome(const Rock&, const Scissors&) { return "Rock beats Scissors"; }
std::string outcome(const Paper&, const Rock&) { return "Paper beats Rock"; }
std::string outcome(const Paper&, const Paper&) { return "a draw"; }
std::string outcome(const Paper&, const Scissors&) { return "Scissors beats Paper"; }
std::string outcome(const Scissors&, const Rock&) { return "Scissors beats Rock"; }
std::string outcome(const Scissors&, const Paper&) { return "Scissors beats Paper"; }
std::string outcome(const Scissors&, const Scissors&) { return "a draw"; }

4. 实现两个访问者

// The visitor for the second dispatch. It is templated on the type of the
// first move, so that inside every overload both types are known and the
// right outcome() overload can be selected.
template<typename First>
class OpponentVisitor : public Visitor {
public:
    explicit OpponentVisitor(First& first) : first_(first) {}

    void visit(Rock& second) override { result_ = outcome(first_, second); }
    void visit(Paper& second) override { result_ = outcome(first_, second); }
    void visit(Scissors& second) override { result_ = outcome(first_, second); }

    const std::string& result() const { return result_; }

private:
    First& first_;
    std::string result_;
};

// The visitor for the first dispatch. It holds the opponent and asks it to
// accept the second visitor.
class MatchVisitor : public Visitor {
public:
    explicit MatchVisitor(Element& opponent) : opponent_(opponent) {}

    void visit(Rock& rock) override {
        OpponentVisitor<Rock> visitor(rock);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    void visit(Paper& paper) override {
        OpponentVisitor<Paper> visitor(paper);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    void visit(Scissors& scissors) override {
        OpponentVisitor<Scissors> visitor(scissors);
        opponent_.accept(visitor);
        result_ = visitor.result();
    }

    const std::string& result() const { return result_; }

private:
    Element& opponent_;
    std::string result_;
};

5. 把两次分派串起来

// One round: the first dispatch picks the overload for the first move, the
// second dispatch picks the overload for the second move.
std::string playRound(Element& a, Element& b) {
    MatchVisitor visitor(b);
    a.accept(visitor);
    return visitor.result();
}

int main() {
    Rock rock;
    Paper paper;
    Scissors scissors;

    std::cout << "Rock vs Paper:    " << playRound(rock, paper) << "\n";
    std::cout << "Rock vs Scissors: " << playRound(rock, scissors) << "\n";
    std::cout << "Paper vs Rock:    " << playRound(paper, rock) << "\n";
    std::cout << "Paper vs Paper:   " << playRound(paper, paper) << "\n";
    std::cout << "Scissors vs Rock: " << playRound(scissors, rock) << "\n";
    std::cout << "Scissors vs Paper:" << playRound(scissors, paper) << "\n";

    return 0;
}

现代 C++ 实现

使用 std::variant 与 std::visit

#include <variant>

// C++17: std::visit performs the same double dispatch for you. The
// overload set is picked by the two alternative types of the variants.
using Move = std::variant<Rock, Paper, Scissors>;

std::string playRoundVariant(const Move& a, const Move& b) {
    return std::visit(
        [](const auto& first, const auto& second) {
            return outcome(first, second);
        },
        a, b);
}

使用 if constexpr

#include <type_traits>

// C++17: when both types are known at compile time, the compiler can do
// the dispatch on its own and no visitor is needed at all.
template<typename First, typename Second>
std::string outcomeIfConstexpr(const First&, const Second&) {
    if constexpr (std::is_same_v<First, Rock> && std::is_same_v<Second, Paper>) {
        return "Paper beats Rock";
    } else if constexpr (std::is_same_v<First, Paper> &&
                         std::is_same_v<Second, Scissors>) {
        return "Scissors beats Paper";
    } else {
        return "a draw";
    }
}

使用类型对象

#include <string>
#include <vector>

// The relation between the moves can also live in data: one entry per
// move instead of one entry per pair of moves.
struct MoveType {
    std::string name;
    std::string beats;
};

const std::vector<MoveType> moveTypes = {
    {"Rock", "Scissors"},
    {"Paper", "Rock"},
    {"Scissors", "Paper"},
};

std::string outcomeByName(const std::string& a, const std::string& b) {
    for (const auto& type : moveTypes) {
        if (type.name != a) {
            continue;
        }
        if (a == b) {
            return "a draw";
        }
        return type.beats == b ? a + " beats " + b : b + " beats " + a;
    }
    return "unknown";
}

与相关模式的区别

模式 区别
访问者模式 访问者模式只按一种类型分派;双重分派需要两个操作数的类型
策略模式 策略模式为一个对象挑一个算法;双重分派从一对操作数里挑行为
类型对象模式 类型对象模式用数据替掉类层次;双重分派保留类层次,只是分派两次
重载 重载按静态类型选择;双重分派按运行时类型选择

最佳实践

1. 让被访问的类保持精简

// The move classes carry their own data and nothing else. Every operation
// lives in a visitor, so a new operation never touches them.
class Rock : public Element {
public:
    void accept(Visitor& visitor) override { visitor.visit(*this); }
    std::string name() const override { return "Rock"; }
};

2. 把配对表放在运算旁边

// The table belongs to the operation, not to the move classes.
std::string outcome(const Rock&, const Scissors&) { return "Rock beats Scissors"; }
std::string outcome(const Scissors&, const Rock&) { return "Scissors beats Rock"; }

3. 一个访问者只做一件事

// A second operation is a second visitor. The moves are not touched.
class CountVisitor : public Visitor {
public:
    void visit(Rock&) override { ++count_; }
    void visit(Paper&) override { ++count_; }
    void visit(Scissors&) override { ++count_; }

    int count() const { return count_; }

private:
    int count_ = 0;
};

常见陷阱

陷阱 1:用一次分派干两次分派的活

// Not recommended: the visitor only ever sees the first move, so the
// result is wrong for every pair but the first.
class BrokenVisitor : public Visitor {
public:
    void visit(Rock&) override { result_ = "Rock wins"; }
    void visit(Paper&) override { result_ = "Paper wins"; }
    void visit(Scissors&) override { result_ = "Scissors wins"; }

    const std::string& result() const { return result_; }

private:
    std::string result_;
};

陷阱 2:忘了第二次分派

// Not recommended: the opponent is never asked, so the second move is
// silently replaced by the first one and the table answers the wrong entry.
class OneSidedVisitor : public Visitor {
public:
    void visit(Rock& rock) override { result_ = outcome(rock, rock); }
    void visit(Paper& paper) override { result_ = outcome(paper, paper); }
    void visit(Scissors& scissors) override { result_ = outcome(scissors, scissors); }

    const std::string& result() const { return result_; }

private:
    std::string result_;
};

陷阱 3:通过没有虚析构的基类删除对象

// Not recommended: the visitor base has no virtual destructor, so a
// visitor that is deleted through a base pointer is destroyed wrongly.
class VisitorWithoutDestructor {
public:
    virtual void visit(Rock& rock) = 0;
    virtual void visit(Paper& paper) = 0;
    virtual void visit(Scissors& scissors) = 0;
};

// Recommended: give the base class a virtual destructor.
class VisitorWithDestructor {
public:
    virtual ~VisitorWithDestructor() = default;
    virtual void visit(Rock& rock) = 0;
    virtual void visit(Paper& paper) = 0;
    virtual void visit(Scissors& scissors) = 0;
};

示例

这个主题的可运行版本:

总结

双重分派的核心要点:

  • 适用场景:一个运算依赖两个对象的运行时类型,单次虚函数调用不够用
  • 核心优点:算结果的地方两个运行时类型都已知,运算不必待在被访问的类里
  • 实现要点:分派两次——先调第一个操作数的 accept(),再调第二个操作数的 accept()——并且把配对表放在运算旁边
  • 常见陷阱:用一次分派干两次分派的活、忘了第二次分派、通过没有虚析构的基类删除访问者

记住:双重分派的关键是分派两次——第一个操作数挑出访问者的重载,第二个操作数挑出真正的运算。

另请参阅