跳转至

第三章 概念、需求和约束

concept是为了解决泛型编程中类型的约束问题. 语义上其实就是显示地写出要求存在的api/结构体等

namespace greater_cpp_20 {

template <typename T>
concept IsPointer = requires(T p) {
    *p;                                     // 检查 T 是否可以解引用
    p == nullptr;                           // 检查 T 是否可以与 nullptr 比较
    { p < p } -> std::convertible_to<bool>; // 检查 T 是否可以进行小于比较
};

template <typename T>
    requires(!std::is_pointer_v<T>)
T maxValue(const T &a, const T &b) {
    return a < b ? b : a;
}

template <typename T>
    requires IsPointer<T>
auto maxValue2(T a, T b) {
    // return *a < *b ? *b : *a;
    return maxValue(*a, *b); // 这里可以调用非指针版本的 maxValue
}

auto maxValue3(IsPointer auto a, IsPointer auto b) {
    // return *a < *b ? *b : *a;
    return maxValue(*a, *b); // 这里可以调用非指针版本的 maxValue
}

void test_maxValue() {
    int a = 5, b = 10;
    double x = 3.14, y = 2.71;
    fmt::print("Max of {} and {} is {}\n", a, b, maxValue(a, b));
    fmt::print("Max of {} and {} is {}\n", x, y, maxValue(x, y));

    // maxValue(&a, &b); // compile error: T is not a pointer type
    maxValue2(&a, &b); // compile error: T is not a pointer type
    maxValue3(&a, &b); // compile error: T is not a pointer type
}
} // namespace greater_cpp_20