C++ 模板专题 - 参数约束

一:概述:

        除了使用SFINAE对模板参数进行约束之外,还可以使用概念(Concepts)来对模板参数进行约束,确保传入的类似满足特定条件。概念(Concepts)是C++20中引入的,概念是用于指定类型要求的一种机制。它们可以帮助你编写更清晰的代码,通过限制模板参数类型来提高类型安全性和可读性。requires 关键字用于定义这些类型要求,是C++20中为概念(Concepts)引入的关键字。

二:例子

#include <concepts>
#include <iostream>

// 定义一个概念,要求类型 T 必须支持加法操作
template<typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::same_as<T>; // 要求 a + b 的结果类型与 T 相同
};

// 使用 Addable 概念约束模板参数
template<Addable T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(3, 4) << '\n'; // 输出 7
    // std::cout << add("Hello", "World"); // 这将导致编译错误,因为字符串不支持加法
}
#include <iostream>
#include <vector>

template <typename>
struct Other;

template <>
struct Other<std::vector<int>> {};

template<typename T> 
concept TypeRequirement = requires {
    typename T::value_type; 
    typename Other<T>;     
};

int main() {

    std::cout << '\n';

    TypeRequirement auto myVec= std::vector<int>{1, 2, 3};

    std::cout << '\n';

}

猜你喜欢

转载自blog.csdn.net/zg260/article/details/143314342