// C++20 示例代码:使用 Concepts 和 Ranges 库
#include <iostream>
#include <ranges>
#include <vector>
// 使用 Concepts 定义一个模板函数,只接受可加类型
template<typename T>
concept Addable = requires(T a, T b) {
{ a + b } -> std::same_as<T>;
};
void print_addable(Addable auto a, Addable auto b) {
std::cout << "Sum: " << (a + b) << std::endl;
}
int main() {
// 使用 Ranges 库进行范围操作
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用 ranges::views 进行过滤和转换
auto even_squares = vec | std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
std::cout << "Even squares: ";
for (auto val : even_squares) {
std::cout << val << " ";
}
std::cout << std::endl;
// 测试 Concepts 函数
print_addable(3, 4); // 正确:3 + 4 = 7
// print_addable("hello", "world"); // 错误:字符串连接不符合 Addable 概念
return 0;
}
Concepts:
template<typename T> concept Addable 定义了一个概念 Addable,它要求类型 T 支持加法运算,并且返回值类型与 T 相同。print_addable 函数仅接受符合 Addable 概念的参数类型,确保传入的参数支持加法运算。Ranges 库:
std::vector<int> vec 创建了一个整数向量。std::views::filter 和 std::views::transform 对向量进行过滤和转换操作。这里我们过滤出偶数并将其平方。even_squares 是一个视图(view),不会立即计算结果,只有在遍历时才会生成结果。主函数:
print_addable 函数,传入两个整数,输出它们的和。print_addable 传入字符串会导致编译错误,因为字符串连接不符合 Addable 概念。这段代码展示了 C++20 中两个重要的新特性:Concepts 和 Ranges 库。
上一篇:c++sort函数的用法
下一篇:c++map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站