类型擦除

类型擦除(Type Erasure)是一种在运行时隐藏具体类型,仅暴露行为接口的技术。它让我们能够将不相关的类型统一存储和操作,同时保持值语义。标准库中的 std::function 和 std::any 就是类型擦除的经典应用。

什么是类型擦除

类型擦除的核心思想:编译时知道具体类型,但存储时"忘记"它,只保留需要的操作接口。

// 没有类型擦除:必须知道具体类型
auto fn1 = [](int x) { return x * 2; };       // lambda 类型独一无二
auto fn2 = [](int x) { return x + 10; };      // 另一个不同类型
// decltype(fn1) != decltype(fn2),无法放入同一容器

// 有了类型擦除:std::function 隐藏了具体类型
std::function<int(int)> f1 = [](int x) { return x * 2; };
std::function<int(int)> f2 = [](int x) { return x + 10; };
// 同一类型!可以放入容器
std::vector<std::function<int(int)>> funcs = {f1, f2};

std::function:最常见的类型擦除

std::function 擦除了可调用对象的具体类型,只保留签名信息:

#include <functional>
#include <iostream>

// 普通函数
int add_one(int x) { return x + 1; }

// 函数对象
struct Multiplier {
    int factor;
    int operator()(int x) const { return x * factor; }
};

int main() {
    // 所有可调用对象统一为 std::function<int(int)>
    std::function<int(int)> f;

    f = add_one;                          // 函数指针
    std::cout << f(5) << "\n";           // 6

    f = Multiplier{3};                    // 函数对象
    std::cout << f(5) << "\n";           // 15

    f = [](int x) { return x * x; };     // lambda
    std::cout << f(5) << "\n";           // 25
}

std::function 的开销

  • 小对象优化(SBO):小 lambda 直接存储在 function 内部(通常 16-32 字节)
  • 大对象:超过 SBO 缓冲区的可调用对象需要堆分配
  • 调用开销:通过函数指针间接调用,无法内联
  • 如果不需要运行时多态,优先使用模板参数或 auto

std::any:类型安全的 void*

std::any 可以存储任意类型的值,是 void* 的类型安全替代:

#include <any>
#include <string>
#include <iostream>

int main() {
    std::any value;

    value = 42;                            // 存储 int
    std::cout << std::any_cast<int>(value) << "\n";

    value = std::string("hello");          // 存储 string
    std::cout << std::any_cast<std::string>(value) << "\n";

    value = 3.14;                          // 存储 double

    // 类型不匹配时抛出异常
    try {
        auto s = std::any_cast<std::string>(value);
    } catch (const std::bad_any_cast& e) {
        std::cout << "错误: " << e.what() << "\n";
    }

    // 安全检查
    if (value.type() == typeid(double)) {
        std::cout << "是 double: " << std::any_cast<double>(value) << "\n";
    }
}

std::any vs std::variant

std::any 适合完全未知类型(如配置系统、属性映射),但失去了编译时类型检查。如果类型集合已知,std::variant 更安全、更高效。

Sean Parent 类型擦除技术

这是最强大的手写类型擦除模式,由 Sean Parent 在其著名的 "Inheritance is the Base Class of Evil" 演讲中推广。其核心是 Concept + Model + Wrapper 三层结构:

#include <memory>
#include <iostream>
#include <vector>

// Drawable:一个支持 draw() 操作的类型擦除包装器
class Drawable {
public:
    // 模板构造函数:接受任何有 draw() 方法的类型
    template<typename T>
    Drawable(T obj)
        : pimpl_(std::make_unique<Model<T>>(std::move(obj))) {}

    // 拷贝构造(深拷贝)
    Drawable(const Drawable& other)
        : pimpl_(other.pimpl_->clone()) {}

    Drawable(Drawable&&) noexcept = default;

    Drawable& operator=(const Drawable& other) {
        pimpl_ = other.pimpl_->clone();
        return *this;
    }
    Drawable& operator=(Drawable&&) noexcept = default;

    // 对外接口
    void draw() const { pimpl_->draw(); }

private:
    // Concept:内部抽象基类,定义需要的操作
    struct Concept {
        virtual ~Concept() = default;
        virtual void draw() const = 0;
        virtual std::unique_ptr<Concept> clone() const = 0;
    };

    // Model:模板派生类,持有具体类型的值
    template<typename T>
    struct Model final : Concept {
        T data_;
        explicit Model(T obj) : data_(std::move(obj)) {}
        void draw() const override { data_.draw(); }
        std::unique_ptr<Concept> clone() const override {
            return std::make_unique<Model>(data_);
        }
    };

    std::unique_ptr<Concept> pimpl_;
};

现在任何具有 draw() 方法的类型都可以被存储,无需继承任何基类:

// 这些类型完全独立,没有任何继承关系!
struct Circle {
    double radius;
    void draw() const {
        std::cout << "○ Circle r=" << radius << "\n";
    }
};

struct Square {
    double side;
    void draw() const {
        std::cout << "□ Square s=" << side << "\n";
    }
};

struct Text {
    std::string content;
    void draw() const {
        std::cout << "T \"" << content << "\"\n";
    }
};

int main() {
    // 不同类型统一存入同一个 vector!
    std::vector<Drawable> canvas;
    canvas.emplace_back(Circle{3.0});
    canvas.emplace_back(Square{2.5});
    canvas.emplace_back(Text{"Hello C++"});

    // 值语义:可以自由拷贝
    auto canvas_copy = canvas;

    for (const auto& item : canvas_copy) {
        item.draw();
    }
    // 输出:
    // ○ Circle r=3
    // □ Square s=2.5
    // T "Hello C++"
}

类型擦除 vs 继承 vs variant

类型擦除结合了两者的优点:像 variant 一样是值类型,像继承一样支持开放的类型集合。被包装的类型不需要知道自己会被擦除,实现了真正的解耦。

支持多个操作的类型擦除

// 支持 draw() 和 area() 两个操作
class Shape {
public:
    template<typename T>
    Shape(T obj) : pimpl_(std::make_unique<Model<T>>(std::move(obj))) {}

    Shape(const Shape& other) : pimpl_(other.pimpl_->clone()) {}
    Shape(Shape&&) noexcept = default;
    Shape& operator=(Shape other) {   // copy-and-swap
        pimpl_ = std::move(other.pimpl_);
        return *this;
    }

    void draw() const   { pimpl_->draw(); }
    double area() const { return pimpl_->area(); }

private:
    struct Concept {
        virtual ~Concept() = default;
        virtual void draw() const = 0;
        virtual double area() const = 0;
        virtual std::unique_ptr<Concept> clone() const = 0;
    };

    template<typename T>
    struct Model final : Concept {
        T data_;
        explicit Model(T obj) : data_(std::move(obj)) {}
        void draw() const override   { data_.draw(); }
        double area() const override { return data_.area(); }
        std::unique_ptr<Concept> clone() const override {
            return std::make_unique<Model>(data_);
        }
    };

    std::unique_ptr<Concept> pimpl_;
};

何时使用类型擦除

场景 推荐方案
类型集合已知且固定 std::variant
类型集合开放,需要指针语义 虚函数继承
类型集合开放,需要值语义 类型擦除
只需存储可调用对象 std::function / std::move_only_function
存储任意类型但不需要操作 std::any

性能考虑

// 带小对象优化(SBO)的类型擦除
class DrawableSBO {
    static constexpr std::size_t BufferSize = 64;
    static constexpr std::size_t BufferAlign = alignof(std::max_align_t);

    struct Concept { /* 同上 */ };

    template<typename T>
    struct Model final : Concept { /* 同上 */ };

    // 使用 aligned_storage 避免小对象堆分配
    alignas(BufferAlign) std::byte buffer_[BufferSize];
    Concept* ptr_ = nullptr;  // 指向 buffer_ 或堆
    bool on_heap_ = false;

public:
    template<typename T>
    DrawableSBO(T obj) {
        if constexpr (sizeof(Model<T>) <= BufferSize
                      && alignof(Model<T>) <= BufferAlign) {
            // 小对象:就地构造在 buffer_ 中
            ptr_ = new (buffer_) Model<T>(std::move(obj));
            on_heap_ = false;
        } else {
            // 大对象:堆分配
            ptr_ = new Model<T>(std::move(obj));
            on_heap_ = true;
        }
    }
    // ... 析构函数需要根据 on_heap_ 选择 delete 还是手动调用析构
};

性能对比

  • 无 SBO:每次构造都堆分配,但实现简单
  • 有 SBO:小对象避免堆分配,但增加了代码复杂度
  • std::function 内部已经实现了 SBO(通常 16-32 字节缓冲区)
  • 在性能关键路径上,先测量再优化——SBO 未必总是赢家(增大了对象本身的尺寸)

本章小结

  • 类型擦除隐藏具体类型,只暴露行为接口,适合开放类型集 + 值语义的需求
  • std::function 是最常用的类型擦除,擦除可调用对象的具体类型
  • std::any 是类型安全的 void*,适合完全未知类型的存储
  • Sean Parent 的 Concept + Model + Wrapper 模式是手写类型擦除的标准范式
  • 小对象优化(SBO)可以避免堆分配,但需权衡实现复杂度