[ PROMPT_NODE_24600 ]
modern-cpp
[ SKILL_DOCUMENTATION ]
# 现代 C++20/23 特性
## 概念与约束 (Concepts)
cpp
#include
// 定义自定义概念
template
concept Numeric = std::integral || std::floating_point;
template
concept Hashable = requires(T a) {
{ std::hash{}(a) } -> std::convertible_to;
};
template
concept Container = requires(T c) {
typename T::value_type;
typename T::iterator;
{ c.begin() } -> std::same_as;
{ c.end() } -> std::same_as;
{ c.size() } -> std::convertible_to;
};
// 使用概念进行函数约束
template
T add(T a, T b) {
return a + b;
}
// 基于概念的重载
template
void process(T value) {
std::cout << "处理整数: " << value << 'n';
}
template
void process(T value) {
std::cout << "处理浮点数: " << value << 'n';
}
## 范围库 (Ranges) 与视图 (Views)
cpp
#include
#include
#include
// 基于范围的算法
std::vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 过滤、转换、获取 - 均为惰性求值
auto result = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; })
| std::views::take(3);
// 仅在需要时复制到 vector
std::vector materialized(result.begin(), result.end());
// 自定义范围适配器
auto is_even = [](int n) { return n % 2 == 0; };
auto square = [](int n) { return n * n; };
auto pipeline = std::views::filter(is_even)
| std::views::transform(square);
auto processed = numbers | pipeline;
## 协程 (Coroutines)
cpp
#include
#include
#include
// 生成器协程
template
struct Generator {
struct promise_type {
T current_value;
auto get_return_object() {
return Generator{std::coroutine_handle::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
std::suspend_always yield_value(T value) {
current_value = value;
return {};
}
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle handle;
Generator(std::coroutine_handle h) : handle(h) {}
~Generat