1. 概念(Concepts)
概念是 C++20 引入的一项重要特性,它允许程序员定义类型约束,从而在编译时检查模板参数是否符合某些要求。概念提供了模板参数的限制,使得模板代码更加可读和易于维护。
示例代码:
#include <iostream>
#include <concepts>// 定义一个概念,要求类型必须支持 "==" 操作符
template <typename T>
concept EqualityComparable = requires(T a, T b) {{ a == b } -> std::convertible_to<bool>;
};// 使用概念约束模板
template <EqualityComparable T>
bool are_equal(const T& a, const T& b) {return a == b;
}int main() {int x = 10, y = 10;std::cout << "Are x and y equal? " << are_equal(x, y) << std::endl;// 编译错误:std::string 不支持此概念的 "==" 操作符// std::string s1 = "Hello", s2 = "World";// std::cout << are_equal(s1, s2) << std::endl;
}
2. 范围(Ranges)库
C++20 引入了 ranges
库,它提供了一组新的算法和视图操作,使得处理序列(如容器和数组)更加简单和灵活。
示例代码:
#include <iostream>
#include <ranges>
#include <vector>int main() {std::vector<int> nums = {1, 2, 3, 4, 5};// 使用 ranges 处理序列auto even_nums = nums | std::ranges::views::filter([](int n) { return n % 2 == 0; });std::cout << "Even numbers: ";for (int n : even_nums) {std::cout << n << " ";}std::cout << std::endl;
}
3. 协程(Coroutines)
协程是 C++20 引入的重要特性之一,它使得异步编程更加简洁。通过 co_await
, co_yield
, 和 co_return
关键字,C++20 提供了对协程的支持。
示例代码:
#include <iostream>
#include <coroutine>// 简单的协程例子
struct Generator {struct promise_type {int value;auto get_return_object() { return Generator{*this}; }auto initial_suspend() { return std::suspend_always{}; }auto final_suspend() noexcept { return std::suspend_always{}; }void return_void() {}void unhandled_exception() {}auto yield_value(int val) {value = val;return std