C++20:四大特性及更多
探索 C++20 的变革性特性:概念、范围、太空船运算符、std::format、指定初始化器、std::span 等。
C++20:跨时代的飞跃
C++20 是自 C++11 以来对 C++ 最重要的更新。它引入了四大特性 ── 概念(Concepts)、范围(Ranges)、协程(Coroutines)和模块(Modules) ── 每一个都从根本上改变了 C++ 代码的编写方式。除了「四大特性」之外,C++20 还带来了太空船运算符、std::format、std::span、指定初始化器以及许多 constexpr 增强。本课涵盖除协程和模块之外的所有内容,它们有专门的课程。
概念:约束模板
概念用可读、可组合的模板参数约束替代 SFINAE。当约束不满足时,它们会产生清晰的错误消息:
#include <iostream>
#include <concepts>
#include <string>
#include <vector>
#include <numeric>
// Define a custom concept
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
// Use concept in a requires clause
template<typename T>
requires Numeric<T>
T add(T a, T b) {
return a + b;
}
// Shorthand syntax — concept as type constraint
auto multiply(Numeric auto a, Numeric auto b) {
return a * b;
}
// Concept with multiple requirements
template<typename Container>
concept Summable = requires(Container c) {
{ c.begin() } -> std::input_or_output_iterator;
{ c.end() } -> std::input_or_output_iterator;
{ c.size() } -> std::convertible_to<std::size_t>;
};
template<Summable Container>
auto sum_container(const Container& c) {
using T = typename Container::value_type;
return std::accumulate(c.begin(), c.end(), T{});
}
int main() {
std::cout << add(3, 4) << "\n"; // 7
std::cout << multiply(2.5, 4.0) << "\n"; // 10.0
std::vector<int> v{1, 2, 3, 4, 5};
std::cout << sum_container(v) << "\n"; // 15
// add(std::string("a"), std::string("b")); // Compile error!
// Error message: constraints not satisfied — Numeric<std::string> is false
return 0;
}范围:可组合的算法
范围为 STL 带来了函数式的管道风格方法。视图是惰性的 ── 它们不分配或拷贝数据,组合的转换仅在迭代时才执行:
#include <iostream>
#include <ranges>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<int> numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Pipeline: filter even, square them, take first 3
auto result = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; })
| std::views::take(3);
for (int n : result) {
std::cout << n << " "; // 4 16 36
}
std::cout << "\n";
// Range-based algorithms with projections
struct Employee {
std::string name;
int salary;
};
std::vector<Employee> team{
{"Alice", 90000}, {"Bob", 75000}, {"Carol", 120000}
};
// Sort by salary using a projection — no custom comparator needed
std::ranges::sort(team, {}, &Employee::salary);
for (const auto& e : team) {
std::cout << e.name << ": " << e.salary << "\n";
}
// iota generates an infinite sequence
for (int i : std::views::iota(1) | std::views::take(5)) {
std::cout << i << " "; // 1 2 3 4 5
}
std::cout << "\n";
return 0;
}三路比较与指定初始化器
太空船运算符 <=> 通过单个声明生成全部六个比较运算符。指定初始化器将 C 语言的命名字段初始化引入 C++ 并增加了类型安全:
#include <iostream>
#include <compare>
#include <string>
struct Version {
int major;
int minor;
int patch;
// One operator generates ==, !=, <, >, <=, >=
auto operator<=>(const Version&) const = default;
};
struct Config {
std::string host = "localhost";
int port = 8080;
bool ssl = false;
int max_connections = 100;
};
int main() {
Version v1{2, 0, 0};
Version v2{1, 9, 5};
if (v1 > v2) std::cout << "v1 is newer\n"; // true
if (v1 != v2) std::cout << "versions differ\n";
// Strong ordering gives you all 6 operators for free
auto cmp = v1 <=> v2;
if (cmp > 0) std::cout << "v1 > v2\n";
// Designated initializers — name the fields you're setting
Config cfg{
.host = "example.com",
.port = 443,
.ssl = true
// .max_connections keeps its default value (100)
};
std::cout << cfg.host << ":" << cfg.port
<< " SSL=" << std::boolalpha << cfg.ssl
<< " max=" << cfg.max_connections << "\n";
return 0;
}std::format 与 std::span
std::format 为 C++ 带来了 Python 风格的字符串格式化。std::span 是对连续元素序列的非拥有视图,替代原始的指针+大小对:
#include <iostream>
#include <format>
#include <span>
#include <vector>
#include <array>
// std::span — works with any contiguous container
void print_values(std::span<const int> data) {
for (int v : data) {
std::cout << std::format("{:>5}", v);
}
std::cout << "\n";
}
int main() {
// std::format — type-safe, positional formatting
std::string msg = std::format("Hello, {}! You are {} years old.", "Alice", 30);
std::cout << msg << "\n";
// Format specifiers
std::cout << std::format("Hex: {:#x}, Oct: {:#o}, Bin: {:#b}\n", 255, 255, 255);
std::cout << std::format("Pi: {:.4f}\n", 3.14159265);
std::cout << std::format("{:<15} {:>10}\n", "Name", "Score");
std::cout << std::format("{:<15} {:>10}\n", "Alice", 95);
// std::span — unifies arrays, vectors, and raw buffers
int c_array[] = {1, 2, 3, 4, 5};
std::vector<int> vec{6, 7, 8, 9, 10};
std::array<int, 3> arr{11, 12, 13};
print_values(c_array); // works with C array
print_values(vec); // works with vector
print_values(arr); // works with std::array
// Subspan — slice without copying
std::span<int> full(vec);
auto first_three = full.subspan(0, 3);
print_values(first_three); // 6 7 8
return 0;
}constexpr 增强与 Chrono
C++20 大幅扩展了 constexpr 的适用范围:虚函数、dynamic_cast、try-catch,甚至 std::vector 和 std::string 现在都可以在 constexpr 上下文中使用。这意味着更多计算转移到编译时,从而产生更快的运行时代码。
库增加了完整的日历和时区系统。你可以表示像 2024y/January/15 这样的日期,进行日历算术运算,以及在时区之间转换 ── 全部类型安全,无需外部库。
属性:[[likely]] 和 [[unlikely]] 向编译器提示哪些分支是热路径,从而在性能关键部分实现更好的代码生成。
你不必一次性使用 C++20 的所有特性。从那些以最小干扰带来最大生产力提升的特性开始:
1. 太空船运算符 ── 立即为你的类型添加 auto operator<=>(const T&) const = default;
2. 概念 ── 在编写自定义概念之前先使用标准概念(std::integral、std::ranges::range)
3. std::format ── 替换 printf 和 stringstream 格式化
4. 范围 ── 在新代码中从 std::views::filter 和 std::views::transform 开始
5. 指定初始化器 ── 用于配置结构体和选项类型
将协程和模块留到你的团队和工具链准备就绪时再使用。
- 概念用可读、可组合的模板约束和清晰的错误消息替代 SFINAE
- 范围使用
|运算符提供惰性、可组合的管道 ── 无需临时容器 - 太空船运算符
<=>通过一个默认声明生成全部六个比较运算符 std::format为 C++ 带来了类型安全的 Python 风格字符串格式化std::span是对连续内存的非拥有视图,替代指针+大小对- 指定初始化器(
{.field = value})使结构体构造具有自文档性
测验 — 检验你的知识
(20 经验值)1. `auto operator<=>(const MyType&) const = default;` 做了什么?
2. 范围视图(如 `std::views::filter`)的关键优势是什么?
3. C++20 概念解决了什么问题?