实现序列化框架 ​

面试考点 ​

序列化框架是考察 C++ 模板元编程和类型系统设计的综合题目。面试官考察你是否理解二进制序列化的原理、如何用模板特化处理不同类型、如何设计可扩展的序列化接口,以及字节序和对齐等底层问题。

核心概念 ​

序列化是把内存中的对象转换为字节流(可以存储到文件或通过网络传输),反序列化是逆过程。一个好的序列化框架需要:1) 支持基本类型和复合类型;2) 类型安全,反序列化时能检测类型不匹配;3) 可扩展,用户自定义类型可以方便地接入;4) 紧凑的编码减少传输体积。

基本示例 ​

cpp
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cstdint>
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <optional>
#include <tuple>
#include <sstream>

// ============================
// 字节缓冲区
// ============================

class ByteBuffer {
public:
    // 写入原始字节
    void write(const void* data, size_t size) {
        const auto* bytes = static_cast<const uint8_t*>(data);
        buffer_.insert(buffer_.end(), bytes, bytes + size);
    }

    // 读取原始字节
    void read(void* data, size_t size) {
        if (read_pos_ + size > buffer_.size()) {
            throw std::runtime_error("反序列化越界: 剩余字节不足");
        }
        std::memcpy(data, buffer_.data() + read_pos_, size);
        read_pos_ += size;
    }

    // 获取缓冲区数据
    const std::vector<uint8_t>& data() const { return buffer_; }
    size_t size() const { return buffer_.size(); }
    size_t remaining() const { return buffer_.size() - read_pos_; }

    // 重置读取位置
    void reset_read() { read_pos_ = 0; }

    // 从字节数组加载
    void load(const std::vector<uint8_t>& data) {
        buffer_ = data;
        read_pos_ = 0;
    }

private:
    std::vector<uint8_t> buffer_;
    size_t read_pos_ = 0;
};

// ============================
// 序列化器:模板特化实现
// ============================

// 前置声明
template<typename T, typename Enable = void>
struct Serializer;

// 序列化/反序列化的统一接口
template<typename T>
void serialize(ByteBuffer& buf, const T& value) {
    Serializer<T>::serialize(buf, value);
}

template<typename T>
void deserialize(ByteBuffer& buf, T& value) {
    Serializer<T>::deserialize(buf, value);
}

// 反序列化并返回值
template<typename T>
T deserialize(ByteBuffer& buf) {
    T value;
    Serializer<T>::deserialize(buf, value);
    return value;
}

// ============================
// 基本类型的序列化(算术类型)
// ============================

// 对所有算术类型(int, float, double, char, bool 等)
// 直接按内存布局写入/读取
template<typename T>
struct Serializer<T, std::enable_if_t<std::is_arithmetic_v<T>>> {
    static void serialize(ByteBuffer& buf, const T& value) {
        buf.write(&value, sizeof(T));
    }

    static void deserialize(ByteBuffer& buf, T& value) {
        buf.read(&value, sizeof(T));
    }
};

// ============================
// 枚举类型
// ============================

template<typename T>
struct Serializer<T, std::enable_if_t<std::is_enum_v<T>>> {
    using UnderlyingType = std::underlying_type_t<T>;

    static void serialize(ByteBuffer& buf, const T& value) {
        auto raw = static_cast<UnderlyingType>(value);
        ::serialize(buf, raw);
    }

    static void deserialize(ByteBuffer& buf, T& value) {
        UnderlyingType raw;
        ::deserialize(buf, raw);
        value = static_cast<T>(raw);
    }
};

// ============================
// std::string
// ============================

template<>
struct Serializer<std::string> {
    static void serialize(ByteBuffer& buf, const std::string& value) {
        // 先写长度,再写内容
        uint32_t len = static_cast<uint32_t>(value.size());
        ::serialize(buf, len);
        buf.write(value.data(), len);
    }

    static void deserialize(ByteBuffer& buf, std::string& value) {
        uint32_t len;
        ::deserialize(buf, len);
        value.resize(len);
        buf.read(value.data(), len);
    }
};

// ============================
// std::vector<T>
// ============================

template<typename T>
struct Serializer<std::vector<T>> {
    static void serialize(ByteBuffer& buf, const std::vector<T>& vec) {
        // 先写元素数量
        uint32_t count = static_cast<uint32_t>(vec.size());
        ::serialize(buf, count);

        // 逐个序列化元素
        for (const auto& item : vec) {
            ::serialize(buf, item);
        }
    }

    static void deserialize(ByteBuffer& buf, std::vector<T>& vec) {
        uint32_t count;
        ::deserialize(buf, count);

        vec.clear();
        vec.reserve(count);
        for (uint32_t i = 0; i < count; i++) {
            T item;
            ::deserialize(buf, item);
            vec.push_back(std::move(item));
        }
    }
};

// ============================
// std::optional<T>
// ============================

template<typename T>
struct Serializer<std::optional<T>> {
    static void serialize(ByteBuffer& buf, const std::optional<T>& opt) {
        bool has_value = opt.has_value();
        ::serialize(buf, has_value);
        if (has_value) {
            ::serialize(buf, *opt);
        }
    }

    static void deserialize(ByteBuffer& buf, std::optional<T>& opt) {
        bool has_value;
        ::deserialize(buf, has_value);
        if (has_value) {
            T value;
            ::deserialize(buf, value);
            opt = std::move(value);
        } else {
            opt = std::nullopt;
        }
    }
};

// ============================
// std::pair<A, B>
// ============================

template<typename A, typename B>
struct Serializer<std::pair<A, B>> {
    static void serialize(ByteBuffer& buf, const std::pair<A, B>& p) {
        ::serialize(buf, p.first);
        ::serialize(buf, p.second);
    }

    static void deserialize(ByteBuffer& buf, std::pair<A, B>& p) {
        ::deserialize(buf, p.first);
        ::deserialize(buf, p.second);
    }
};

// ============================
// std::unordered_map<K, V>
// ============================

template<typename K, typename V>
struct Serializer<std::unordered_map<K, V>> {
    static void serialize(ByteBuffer& buf, const std::unordered_map<K, V>& map) {
        uint32_t count = static_cast<uint32_t>(map.size());
        ::serialize(buf, count);
        for (const auto& [key, value] : map) {
            ::serialize(buf, key);
            ::serialize(buf, value);
        }
    }

    static void deserialize(ByteBuffer& buf, std::unordered_map<K, V>& map) {
        uint32_t count;
        ::deserialize(buf, count);
        map.clear();
        map.reserve(count);
        for (uint32_t i = 0; i < count; i++) {
            K key;
            V value;
            ::deserialize(buf, key);
            ::deserialize(buf, value);
            map.emplace(std::move(key), std::move(value));
        }
    }
};

// ============================
// 用户自定义类型:侵入式序列化
// ============================

// 用户定义的类型只需在类内实现 serialize/deserialize 方法
// 框架通过 SFINAE 自动检测

// 检测是否有 serialize 成员函数
template<typename T, typename = void>
struct has_serialize_method : std::false_type {};

template<typename T>
struct has_serialize_method<T,
    std::void_t<decltype(std::declval<const T>().serialize(std::declval<ByteBuffer&>()))>>
    : std::true_type {};

template<typename T, typename = void>
struct has_deserialize_method : std::false_type {};

template<typename T>
struct has_deserialize_method<T,
    std::void_t<decltype(std::declval<T>().deserialize(std::declval<ByteBuffer&>()))>>
    : std::true_type {};

// 用户自定义类型的序列化(通过成员函数)
template<typename T>
struct Serializer<T, std::enable_if_t<
    has_serialize_method<T>::value &&
    has_deserialize_method<T>::value &&
    !std::is_arithmetic_v<T> &&
    !std::is_enum_v<T>>>
{
    static void serialize(ByteBuffer& buf, const T& value) {
        value.serialize(buf);
    }

    static void deserialize(ByteBuffer& buf, T& value) {
        value.deserialize(buf);
    }
};

// ============================
// 辅助宏:简化自定义类型的序列化
// ============================

// 用于在类中声明序列化方法
// 使用方式:SERIALIZABLE_FIELDS(field1, field2, field3)
#define SERIALIZABLE_FIELDS(...)                               \
    void serialize(ByteBuffer& buf) const {                    \
        serialize_fields(buf, __VA_ARGS__);                    \
    }                                                          \
    void deserialize(ByteBuffer& buf) {                        \
        deserialize_fields(buf, __VA_ARGS__);                  \
    }

// 序列化多个字段的辅助函数
template<typename... Args>
void serialize_fields(ByteBuffer& buf, const Args&... args) {
    (serialize(buf, args), ...);  // C++17 折叠表达式
}

template<typename... Args>
void deserialize_fields(ByteBuffer& buf, Args&... args) {
    (deserialize(buf, args), ...);  // C++17 折叠表达式
}

// ============================
// 使用示例
// ============================

// 自定义类型:玩家信息
struct Player {
    std::string name;
    int32_t level;
    double health;
    std::vector<std::string> inventory;
    std::optional<std::string> guild;

    // 声明可序列化字段
    SERIALIZABLE_FIELDS(name, level, health, inventory, guild)

    void print() const {
        std::cout << "  名称: " << name << std::endl;
        std::cout << "  等级: " << level << std::endl;
        std::cout << "  血量: " << health << std::endl;
        std::cout << "  背包: [";
        for (size_t i = 0; i < inventory.size(); i++) {
            if (i > 0) std::cout << ", ";
            std::cout << inventory[i];
        }
        std::cout << "]" << std::endl;
        std::cout << "  公会: " << guild.value_or("无") << std::endl;
    }
};

// 嵌套的自定义类型
struct GameState {
    int32_t version;
    std::vector<Player> players;
    std::unordered_map<std::string, int32_t> scores;

    SERIALIZABLE_FIELDS(version, players, scores)
};

void test_basic() {
    std::cout << "--- 基本类型序列化 ---" << std::endl;

    ByteBuffer buf;

    // 写入不同类型
    serialize(buf, int32_t(42));
    serialize(buf, 3.14);
    serialize(buf, std::string("hello"));
    serialize(buf, true);

    std::cout << "序列化后大小: " << buf.size() << " 字节" << std::endl;

    // 读取
    buf.reset_read();
    std::cout << "int: " << deserialize<int32_t>(buf) << std::endl;
    std::cout << "double: " << deserialize<double>(buf) << std::endl;
    std::cout << "string: " << deserialize<std::string>(buf) << std::endl;
    std::cout << "bool: " << deserialize<bool>(buf) << std::endl;
}

void test_player() {
    std::cout << "\n--- 自定义类型序列化 ---" << std::endl;

    Player original;
    original.name = "Alice";
    original.level = 50;
    original.health = 95.5;
    original.inventory = {"剑", "盾", "药水"};
    original.guild = "星辰骑士团";

    std::cout << "原始数据:" << std::endl;
    original.print();

    // 序列化
    ByteBuffer buf;
    serialize(buf, original);
    std::cout << "序列化大小: " << buf.size() << " 字节" << std::endl;

    // 反序列化
    buf.reset_read();
    Player restored;
    deserialize(buf, restored);

    std::cout << "还原数据:" << std::endl;
    restored.print();
}

void test_nested() {
    std::cout << "\n--- 嵌套类型序列化 ---" << std::endl;

    GameState state;
    state.version = 1;

    Player p1;
    p1.name = "Bob";
    p1.level = 30;
    p1.health = 80.0;
    p1.inventory = {"弓", "箭"};
    p1.guild = std::nullopt;

    Player p2;
    p2.name = "Carol";
    p2.level = 45;
    p2.health = 100.0;
    p2.inventory = {"法杖"};
    p2.guild = "魔法学院";

    state.players = {p1, p2};
    state.scores = {{"Bob", 1200}, {"Carol", 2500}};

    // 序列化
    ByteBuffer buf;
    serialize(buf, state);
    std::cout << "GameState 序列化大小: " << buf.size() << " 字节" << std::endl;

    // 反序列化
    buf.reset_read();
    GameState restored;
    deserialize(buf, restored);

    std::cout << "版本: " << restored.version << std::endl;
    std::cout << "玩家数: " << restored.players.size() << std::endl;
    for (const auto& p : restored.players) {
        p.print();
    }
    std::cout << "分数:" << std::endl;
    for (const auto& [name, score] : restored.scores) {
        std::cout << "  " << name << ": " << score << std::endl;
    }
}

int main() {
    test_basic();
    test_player();
    test_nested();
    return 0;
}

序列化编码格式 ​

类型编码方式字节数
bool直接写入1
int32_t直接写入4
double直接写入8
string长度(4) + 内容4 + N
vector<T>数量(4) + 元素4 + N*sizeof(T)
optional<T>标志(1) + 值1 [+ sizeof(T)]
自定义类型按字段顺序各字段之和

序列化方案对比 ​

方案速度体积可读性跨语言类型安全
自定义二进制最快最小不可读需要协议编译期检查
JSON慢大可读好运行时
Protocol Buffers快小不可读好IDL 定义
Boost.Serialization快中等不可读仅 C++编译期
本框架快小不可读仅 C++编译期

常见问题 ​

字节序问题怎么处理?

本实现假设序列化和反序列化在同一平台上进行。跨平台通信需要统一字节序,通常用网络字节序(大端)。可以在写入/读取算术类型时加一层 hton/ntoh 转换,或者用变长编码(如 Varint)规避字节序问题。

如何处理版本兼容?

可以在数据头部写入版本号。反序列化时根据版本号选择不同的字段集合。新版本新增的字段用 optional 包装,旧版本数据中没有这些字段时默认为 nullopt。

SERIALIZABLE_FIELDS 宏是怎么工作的?

宏展开为两个成员函数 serialize 和 deserialize,内部用 C++17 折叠表达式 (serialize(buf, args), ...) 对每个字段依次调用序列化。这利用了逗号运算符的求值顺序保证。

适用场景 ​

  • 游戏存档的保存/加载
  • 网络协议的消息编解码
  • 进程间通信(IPC)
  • 内存中对象的持久化

注意事项 ​

  • 字段的序列化顺序必须和反序列化顺序一致
  • 不支持指针和引用类型(需要特殊处理)
  • 跨平台需要考虑字节序和对齐
  • 版本兼容需要额外的版本管理机制
  • 循环引用需要用 ID 映射来打断

总结 ​

序列化框架的核心是模板特化:为每种类型提供 serialize/deserialize 的特化版本。基本类型直接写入内存布局,容器类型先写长度再写元素,自定义类型通过侵入式成员函数或宏展开来序列化各字段。面试中要能实现 ByteBuffer、基本类型和 string/vector 的序列化特化、以及用户自定义类型的接入机制(SFINAE 检测成员函数或宏辅助)。