文档目录

场景:你有一个序列化框架,需要约束参数类型必须支持 serialize 和 deserialize:

// 定义业务相关的 Concept
template <typename T>
concept Serializable = requires(T obj, std::ostream& os, std::istream& is) {
    { obj.serialize(os) } -> std::same_as<void>;
    { obj.deserialize(is) } -> std::same_as<void>;
};

// 使用——读代码的人一眼就知道 T 需要什么能力
template <Serializable T>
void save_to_file(const T& obj, const std::string& path) {
    std::ofstream os(path);
    obj.serialize(os);
}

template <Serializable T>
T load_from_file(const std::string& path) {
    T obj;
    std::ifstream is(path);
    obj.deserialize(is);
    return obj;
}

如果不自定义 Concept 会怎样?

// 没有 Concept 的版本:看不出来 T 需要什么
template <typename T>
void save_to_file(const T& obj, const std::string& path) {
    // 必须写注释告诉用户 T 需要 serialize 方法
    // 但没人读注释,64 行模板报错伺候
}

Concepts 就是自文档化的接口定义。