实现类型安全的 variant ​

面试考点 ​

手写 variant 是考察 C++ 模板元编程能力的经典题目。面试官考察你是否理解标签联合体(tagged union)的原理、aligned_storage 的对齐处理、编译期类型索引、placement new/手动析构,以及 visit 模式的实现。

核心概念 ​

std::variant 本质上是一个类型安全的联合体(tagged union):一块足够大的对齐内存 + 一个类型索引。存储时用 placement new 在这块内存上构造对象,销毁时根据索引调用正确的析构函数。visit 通过索引分发到对应的处理函数。

基本示例 ​

cpp
#include <iostream>
#include <string>
#include <type_traits>
#include <cstddef>
#include <new>
#include <utility>
#include <stdexcept>
#include <functional>

// ============================
// 辅助工具:类型列表操作
// ============================

// 计算多个类型中的最大 sizeof
template<typename... Ts>
struct max_size;

template<typename T>
struct max_size<T> {
    static constexpr size_t value = sizeof(T);
};

template<typename T, typename... Rest>
struct max_size<T, Rest...> {
    static constexpr size_t value =
        sizeof(T) > max_size<Rest...>::value ? sizeof(T) : max_size<Rest...>::value;
};

// 计算多个类型中的最大 alignof
template<typename... Ts>
struct max_align;

template<typename T>
struct max_align<T> {
    static constexpr size_t value = alignof(T);
};

template<typename T, typename... Rest>
struct max_align<T, Rest...> {
    static constexpr size_t value =
        alignof(T) > max_align<Rest...>::value ? alignof(T) : max_align<Rest...>::value;
};

// 在类型列表中查找类型的索引
template<typename T, typename... Ts>
struct type_index;

template<typename T, typename First, typename... Rest>
struct type_index<T, First, Rest...> {
    static constexpr size_t value =
        std::is_same_v<T, First> ? 0 : 1 + type_index<T, Rest...>::value;
};

template<typename T>
struct type_index<T> {
    static_assert(sizeof(T) == 0, "类型不在 variant 的类型列表中");
};

// 根据索引获取类型
template<size_t I, typename... Ts>
struct type_at;

template<typename First, typename... Rest>
struct type_at<0, First, Rest...> {
    using type = First;
};

template<size_t I, typename First, typename... Rest>
struct type_at<I, First, Rest...> {
    using type = typename type_at<I - 1, Rest...>::type;
};

template<size_t I, typename... Ts>
using type_at_t = typename type_at<I, Ts...>::type;

// ============================
// Variant 实现
// ============================

// 无效索引,表示 variant 为空(valueless_by_exception 状态)
constexpr size_t variant_npos = static_cast<size_t>(-1);

template<typename... Ts>
class Variant {
    // 对齐的存储空间:足够大,足够对齐
    alignas(max_align<Ts...>::value)
    char storage_[max_size<Ts...>::value];

    // 当前存储的类型索引
    size_t index_ = variant_npos;

    // ============================
    // 内部辅助:析构当前值
    // ============================

    // 析构函数表:根据索引调用正确的析构函数
    using DestroyFn = void(*)(void*);

    template<typename T>
    static void destroy_impl(void* ptr) {
        static_cast<T*>(ptr)->~T();
    }

    static constexpr DestroyFn destroy_table[] = {
        &destroy_impl<Ts>...
    };

    void destroy_current() {
        if (index_ != variant_npos) {
            destroy_table[index_](storage_);
            index_ = variant_npos;
        }
    }

    // ============================
    // 内部辅助:拷贝构造
    // ============================

    using CopyFn = void(*)(void*, const void*);

    template<typename T>
    static void copy_impl(void* dst, const void* src) {
        new (dst) T(*static_cast<const T*>(src));
    }

    static constexpr CopyFn copy_table[] = {
        &copy_impl<Ts>...
    };

    // ============================
    // 内部辅助:移动构造
    // ============================

    using MoveFn = void(*)(void*, void*);

    template<typename T>
    static void move_impl(void* dst, void* src) {
        new (dst) T(std::move(*static_cast<T*>(src)));
    }

    static constexpr MoveFn move_table[] = {
        &move_impl<Ts>...
    };

public:
    // 默认构造:构造第一个类型
    Variant() {
        using First = type_at_t<0, Ts...>;
        new (storage_) First();
        index_ = 0;
    }

    // 从具体类型构造
    template<typename T,
             typename = std::enable_if_t<(std::is_same_v<std::decay_t<T>, Ts> || ...)>>
    Variant(T&& value) {
        using DecayT = std::decay_t<T>;
        constexpr size_t idx = type_index<DecayT, Ts...>::value;
        new (storage_) DecayT(std::forward<T>(value));
        index_ = idx;
    }

    // 拷贝构造
    Variant(const Variant& other) : index_(other.index_) {
        if (index_ != variant_npos) {
            copy_table[index_](storage_, other.storage_);
        }
    }

    // 移动构造
    Variant(Variant&& other) noexcept : index_(other.index_) {
        if (index_ != variant_npos) {
            move_table[index_](storage_, other.storage_);
        }
    }

    // 拷贝赋值
    Variant& operator=(const Variant& other) {
        if (this != &other) {
            destroy_current();
            index_ = other.index_;
            if (index_ != variant_npos) {
                copy_table[index_](storage_, other.storage_);
            }
        }
        return *this;
    }

    // 移动赋值
    Variant& operator=(Variant&& other) noexcept {
        if (this != &other) {
            destroy_current();
            index_ = other.index_;
            if (index_ != variant_npos) {
                move_table[index_](storage_, other.storage_);
            }
        }
        return *this;
    }

    // 从具体类型赋值
    template<typename T,
             typename = std::enable_if_t<(std::is_same_v<std::decay_t<T>, Ts> || ...)>>
    Variant& operator=(T&& value) {
        using DecayT = std::decay_t<T>;
        constexpr size_t idx = type_index<DecayT, Ts...>::value;
        destroy_current();
        new (storage_) DecayT(std::forward<T>(value));
        index_ = idx;
        return *this;
    }

    // 析构
    ~Variant() {
        destroy_current();
    }

    // 获取当前类型索引
    size_t index() const noexcept { return index_; }

    // 检查是否持有某类型
    template<typename T>
    bool holds_alternative() const {
        constexpr size_t idx = type_index<T, Ts...>::value;
        return index_ == idx;
    }

    // 安全获取值(类型不匹配抛异常)
    template<typename T>
    T& get() {
        constexpr size_t idx = type_index<T, Ts...>::value;
        if (index_ != idx) {
            throw std::bad_variant_access();
        }
        return *reinterpret_cast<T*>(storage_);
    }

    template<typename T>
    const T& get() const {
        constexpr size_t idx = type_index<T, Ts...>::value;
        if (index_ != idx) {
            throw std::bad_variant_access();
        }
        return *reinterpret_cast<const T*>(storage_);
    }

    // 尝试获取(返回指针,类型不匹配返回 nullptr)
    template<typename T>
    T* get_if() {
        constexpr size_t idx = type_index<T, Ts...>::value;
        if (index_ != idx) return nullptr;
        return reinterpret_cast<T*>(storage_);
    }

    template<typename T>
    const T* get_if() const {
        constexpr size_t idx = type_index<T, Ts...>::value;
        if (index_ != idx) return nullptr;
        return reinterpret_cast<const T*>(storage_);
    }

    // 原地构造
    template<typename T, typename... Args>
    T& emplace(Args&&... args) {
        constexpr size_t idx = type_index<T, Ts...>::value;
        destroy_current();
        T* ptr = new (storage_) T(std::forward<Args>(args)...);
        index_ = idx;
        return *ptr;
    }

    // ============================
    // visit 实现
    // ============================

    // visit:对当前值调用 visitor
    template<typename Visitor>
    decltype(auto) visit(Visitor&& vis) {
        return visit_impl(std::forward<Visitor>(vis),
                          std::index_sequence_for<Ts...>{});
    }

    template<typename Visitor>
    decltype(auto) visit(Visitor&& vis) const {
        return visit_impl(std::forward<Visitor>(vis),
                          std::index_sequence_for<Ts...>{});
    }

private:
    // visit 的内部实现:用函数指针表做分发
    template<typename Visitor, size_t... Is>
    decltype(auto) visit_impl(Visitor&& vis, std::index_sequence<Is...>) {
        // 构建函数指针表
        using RetType = decltype(vis(get<type_at_t<0, Ts...>>()));
        using VisitFn = RetType(*)(Visitor&&, void*);

        static constexpr VisitFn table[] = {
            [](Visitor&& v, void* storage) -> RetType {
                return v(*reinterpret_cast<type_at_t<Is, Ts...>*>(storage));
            }...
        };

        return table[index_](std::forward<Visitor>(vis), storage_);
    }

    template<typename Visitor, size_t... Is>
    decltype(auto) visit_impl(Visitor&& vis, std::index_sequence<Is...>) const {
        using RetType = decltype(vis(get<type_at_t<0, Ts...>>()));
        using VisitFn = RetType(*)(Visitor&&, const void*);

        static constexpr VisitFn table[] = {
            [](Visitor&& v, const void* storage) -> RetType {
                return v(*reinterpret_cast<const type_at_t<Is, Ts...>*>(storage));
            }...
        };

        return table[index_](std::forward<Visitor>(vis), storage_);
    }
};

// ============================
// overloaded 辅助(用于 visit)
// ============================

template<class... Fs>
struct overloaded : Fs... {
    using Fs::operator()...;
};

// C++17 推导指引
template<class... Fs>
overloaded(Fs...) -> overloaded<Fs...>;

// ============================
// 测试
// ============================

void test_basic() {
    std::cout << "--- 基本用法 ---" << std::endl;

    Variant<int, double, std::string> v1(42);
    std::cout << "v1 索引: " << v1.index() << std::endl;          // 0
    std::cout << "v1 值: " << v1.get<int>() << std::endl;          // 42
    std::cout << "是 int: " << v1.holds_alternative<int>() << std::endl;  // 1

    v1 = std::string("hello");
    std::cout << "赋值后索引: " << v1.index() << std::endl;        // 2
    std::cout << "v1 值: " << v1.get<std::string>() << std::endl;  // hello

    // 类型不匹配抛异常
    try {
        v1.get<int>();
    } catch (const std::bad_variant_access&) {
        std::cout << "正确:类型不匹配抛异常" << std::endl;
    }

    // get_if:安全获取
    auto* str_ptr = v1.get_if<std::string>();
    auto* int_ptr = v1.get_if<int>();
    std::cout << "string 指针: " << (str_ptr ? "有效" : "空") << std::endl;
    std::cout << "int 指针: " << (int_ptr ? "有效" : "空") << std::endl;
}

void test_copy_move() {
    std::cout << "\n--- 拷贝和移动 ---" << std::endl;

    Variant<int, std::string> v1(std::string("original"));
    Variant<int, std::string> v2 = v1;  // 拷贝
    std::cout << "拷贝后 v2: " << v2.get<std::string>() << std::endl;

    Variant<int, std::string> v3 = std::move(v1);  // 移动
    std::cout << "移动后 v3: " << v3.get<std::string>() << std::endl;
}

void test_emplace() {
    std::cout << "\n--- emplace ---" << std::endl;

    Variant<int, std::string> v;
    v.emplace<std::string>(5, 'x');  // 构造 "xxxxx"
    std::cout << "emplace: " << v.get<std::string>() << std::endl;
}

void test_visit() {
    std::cout << "\n--- visit ---" << std::endl;

    Variant<int, double, std::string> v(3.14);

    // 用 overloaded 模式
    v.visit(overloaded{
        [](int i)    { std::cout << "int: " << i << std::endl; },
        [](double d) { std::cout << "double: " << d << std::endl; },
        [](const std::string& s) { std::cout << "string: " << s << std::endl; }
    });

    v = 42;
    v.visit(overloaded{
        [](int i)    { std::cout << "int: " << i << std::endl; },
        [](double d) { std::cout << "double: " << d << std::endl; },
        [](const std::string& s) { std::cout << "string: " << s << std::endl; }
    });
}

int main() {
    test_basic();
    test_copy_move();
    test_emplace();
    test_visit();
    return 0;
}

variant 内部结构 ​

组件作用实现方式
存储空间存放实际数据alignas 对齐的 char 数组
类型索引记录当前类型size_t,对应类型在参数包中的位置
析构表根据索引调用正确的析构函数指针数组
拷贝表根据索引调用正确的拷贝构造函数指针数组
移动表根据索引调用正确的移动构造函数指针数组

关键技术点 ​

技术用途说明
alignas + char 数组对齐存储大小取所有类型最大值,对齐取最严格
placement new在已有内存上构造new (storage) T(args...)
手动析构销毁已构造的对象ptr->~T()
函数指针表运行时类型分发根据 index 选择正确的函数
变参模板展开生成类型操作表destroy_table[] = {&destroy_impl<Ts>...}

常见问题 ​

为什么不直接用 union?

C++ 的 union 对含有非平凡构造/析构函数的类型(如 std::string)有限制:必须手动管理构造和析构。而且 union 不能用变参模板。用 aligned char 数组 + placement new 更灵活,可以支持任意类型。

visit 是怎么实现的?

核心是函数指针表(jump table):编译期为每个类型生成一个函数指针,运行时根据 index_ 选择对应的函数调用。这比 if-else 链或 switch 更高效(O(1) 查表),也是标准库的典型实现方式。

异常安全怎么处理?

赋值时如果新值的构造抛异常,variant 可能进入"无值"状态(valueless_by_exception)。标准库的 std::variant 用 index = variant_npos 表示这个状态。本实现中,destroy_current 先执行,如果后续构造失败,index 保持 npos。

适用场景 ​

  • 需要存储多种类型之一的场景(JSON 值、AST 节点)
  • 替代继承的轻量级多态
  • 状态机的状态表示
  • 类型安全的 union

注意事项 ​

  • variant 的大小是最大类型的大小 + 索引 + 对齐填充
  • 默认构造会构造第一个类型(第一个类型必须可默认构造)
  • 析构时必须根据索引调用正确的析构函数
  • visit 的 visitor 必须能处理所有可能的类型
  • 赋值操作需要处理异常安全

总结 ​

手写 variant 的关键是:aligned char 数组做存储、size_t 索引记录当前类型、placement new 构造对象、手动调用析构函数、函数指针表做运行时类型分发。面试中要能实现基本的构造/析构/拷贝/移动、get/holds_alternative 访问器,以及基于函数指针表的 visit。核心难点是变参模板展开生成操作表和正确的内存管理。