值语义多态

传统 OOP 使用虚函数和继承来实现多态,但这种方式需要指针/引用和堆分配,带来所有权复杂性和性能损失。现代 C++ 提供了 std::variant + std::visit 的替代方案,可以在封闭类型集上实现多态,同时保持值语义。

传统 OOP 多态回顾

经典的虚函数多态模式如下:

// 经典继承多态:基类定义接口,派生类实现
class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual void draw() const = 0;
};

class Circle : public Shape {
    double radius_;
public:
    explicit Circle(double r) : radius_(r) {}
    double area() const override { return 3.14159 * radius_ * radius_; }
    void draw() const override { std::cout << "Drawing circle r=" << radius_ << "\n"; }
};

class Rectangle : public Shape {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
    void draw() const override { std::cout << "Drawing rect " << w_ << "x" << h_ << "\n"; }
};

// 使用时必须通过指针/引用
void render(const std::vector<std::unique_ptr<Shape>>& shapes) {
    for (const auto& s : shapes) {
        s->draw();
    }
}

传统多态的问题

继承多态的代价

  • 所有权复杂:必须使用指针(unique_ptr 或 shared_ptr),无法直接按值存入容器
  • 堆分配:每个对象都需要 new,频繁分配导致内存碎片
  • 缓存不友好:对象分散在堆上,遍历时 cache miss 严重
  • 切片问题:按值传递会丢失派生类信息
  • 不可拷贝:unique_ptr<Shape> 不能拷贝,需要手动实现 clone()

std::variant + std::visit:值语义多态

std::variant 是一个类型安全的联合体(tagged union),可以持有其模板参数列表中的任意一个类型。配合 std::visit,可以对其中的值进行模式匹配式的分发。

#include <variant>
#include <vector>
#include <iostream>
#include <numbers>

// 各个"形状"类型:普通值类型,无需继承
struct Circle {
    double radius;
};

struct Rectangle {
    double width, height;
};

struct Triangle {
    double base, height;
};

// 用 variant 定义"多态"类型
using Shape = std::variant<Circle, Rectangle, Triangle>;

// 用 visit 实现操作分发
double area(const Shape& shape) {
    return std::visit([](const auto& s) -> double {
        using T = std::decay_t<decltype(s)>;
        if constexpr (std::is_same_v<T, Circle>) {
            return std::numbers::pi * s.radius * s.radius;
        } else if constexpr (std::is_same_v<T, Rectangle>) {
            return s.width * s.height;
        } else {  // Triangle
            return 0.5 * s.base * s.height;
        }
    }, shape);
}

// 使用:全部是值语义!
int main() {
    std::vector<Shape> shapes;
    shapes.push_back(Circle{3.0});          // 无需 new
    shapes.push_back(Rectangle{4.0, 5.0});  // 直接存值
    shapes.push_back(Triangle{6.0, 2.0});

    for (const auto& s : shapes) {
        std::cout << "面积: " << area(s) << "\n";
    }
    // shapes 可以自由拷贝、移动、放入任何容器
}

overloaded 惯用法

使用一个辅助结构体可以让 visit 的代码更加清晰:

// overloaded 辅助模板(C++17)
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };

// C++17 需要推导指引,C++20 不需要
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

// 使用 overloaded 进行模式匹配
void draw(const Shape& shape) {
    std::visit(overloaded{
        [](const Circle& c) {
            std::cout << "○ 圆形 r=" << c.radius << "\n";
        },
        [](const Rectangle& r) {
            std::cout << "□ 矩形 " << r.width << "x" << r.height << "\n";
        },
        [](const Triangle& t) {
            std::cout << "△ 三角形 base=" << t.base << " h=" << t.height << "\n";
        }
    }, shape);
}

两种方案完整对比

下面是同一个 Shape 示例用两种方式实现的完整对比:

// ============ 方案 A:继承多态 ============
class ShapeBase {
public:
    virtual ~ShapeBase() = default;
    virtual double area() const = 0;
    virtual std::string name() const = 0;
    virtual std::unique_ptr<ShapeBase> clone() const = 0;
};

class CircleA : public ShapeBase {
    double r_;
public:
    explicit CircleA(double r) : r_(r) {}
    double area() const override { return std::numbers::pi * r_ * r_; }
    std::string name() const override { return "Circle"; }
    std::unique_ptr<ShapeBase> clone() const override {
        return std::make_unique<CircleA>(*this);
    }
};

// 使用:
std::vector<std::unique_ptr<ShapeBase>> shapes_a;
shapes_a.push_back(std::make_unique<CircleA>(2.0));
// 拷贝需要手动 clone 每个元素...


// ============ 方案 B:variant 多态 ============
struct CircleB { double radius; };
struct RectB   { double width, height; };

using ShapeB = std::variant<CircleB, RectB>;

double area_b(const ShapeB& s) {
    return std::visit(overloaded{
        [](const CircleB& c) { return std::numbers::pi * c.radius * c.radius; },
        [](const RectB& r)   { return r.width * r.height; }
    }, s);
}

// 使用:
std::vector<ShapeB> shapes_b;
shapes_b.push_back(CircleB{2.0});
auto copy = shapes_b;  // 直接拷贝,无需 clone!

何时用 variant vs 继承

维度 std::variant + visit 虚函数继承
类型集合 封闭集(编译时已知所有类型) 开放集(可随时添加新派生类)
添加新类型 需修改 variant 定义,编译器会标记遗漏的 visit 分支 只需新增派生类,无需修改已有代码
添加新操作 新增一个 visit 函数即可 需在所有派生类中添加新虚函数
内存布局 栈上/内联,连续存储,缓存友好 堆分配,指针间接,缓存不友好
值语义 天然可拷贝、可移动 需要 clone() + unique_ptr
空间开销 sizeof = max(各类型) + 判别标签 每个对象有 vptr + 堆分配元数据
运行时开销 跳转表或 if-else 链 虚函数表间接调用
典型场景 AST 节点、消息类型、状态机、配置项 插件系统、GUI 控件、跨库接口

经验法则

如果你的类型集合在编译时就能确定(如 JSON 值 = null | bool | int | double | string | array | object),优先使用 std::variant。如果需要允许第三方代码添加新类型(如插件系统),则继承多态更合适。

variant 的高级用法

// 1. 多个 variant 的联合 visit
using Expr = std::variant<int, double, std::string>;

Expr add(const Expr& lhs, const Expr& rhs) {
    return std::visit(overloaded{
        [](int a, int b) -> Expr { return a + b; },
        [](double a, double b) -> Expr { return a + b; },
        [](const std::string& a, const std::string& b) -> Expr { return a + b; },
        [](auto&&, auto&&) -> Expr {
            throw std::runtime_error("type mismatch");
        }
    }, lhs, rhs);
}

// 2. 递归 variant(用于 AST)
struct Literal;
struct BinOp;
using ExprNode = std::variant<Literal, std::unique_ptr<BinOp>>;

struct Literal { double value; };
struct BinOp {
    char op;
    ExprNode left, right;
};

// 3. variant 作为状态机
struct Idle {};
struct Connecting { std::string host; int port; };
struct Connected  { int socket_fd; };
struct Error      { std::string message; };

using ConnectionState = std::variant<Idle, Connecting, Connected, Error>;

void log_state(const ConnectionState& state) {
    std::visit(overloaded{
        [](const Idle&)         { std::cout << "空闲\n"; },
        [](const Connecting& c) { std::cout << "连接中: " << c.host << "\n"; },
        [](const Connected& c)  { std::cout << "已连接 fd=" << c.socket_fd << "\n"; },
        [](const Error& e)      { std::cout << "错误: " << e.message << "\n"; }
    }, state);
}

variant 的注意事项

  • variant 的大小等于最大类型 + 对齐 + tag,如果某个类型特别大会浪费空间
  • std::get<T>(v) 在类型不匹配时抛出 std::bad_variant_access,优先使用 std::visit
  • std::variant 不能直接递归(类型不完整),需借助 unique_ptr 或 recursive_wrapper
  • C++17 起 variant 默认不允许 valueless_by_exception 状态,但异常安全需注意

本章小结

  • 传统继承多态依赖指针和堆分配,所有权管理复杂且缓存不友好
  • std::variant 在封闭类型集上提供值语义的多态,对象直接存储在栈或容器中
  • std::visit + overloaded 惯用法提供清晰的模式匹配语法
  • variant 适合 AST、消息类型、状态机等已知类型集合的场景
  • 继承多态适合开放扩展、插件系统等需要第三方添加新类型的场景