C++20是C++语言的一个重大更新版本,于2020年9月获得ISO批准。它为语言和STL添加了许多重要的特性,包括格式化库、概念与约束、模块、范围库等。这些新特性对使用STL的方式产生了深远影响。
1.1 格式化文本 —— std::format
背景
C++20引入的 std::format 库提供了类型安全、高效、易用的字符串格式化能力,替代了传统的 printf 和 stringstream 方式。
基本用法
#include <format>
#include <iostream>
int main() {
// 基本格式化
std::string s = std::format("Hello, {}!", "World");
std::cout << s << '\n'; // 输出: Hello, World!
// 带位置参数的格式化
std::string msg = std::format("{1} {0}", "World", "Hello");
std::cout << msg << '\n'; // 输出: Hello World
// 数字格式化
double pi = 3.1415926535;
std::cout << std::format("π = {:.2f}\n", pi); // 输出: π = 3.14
// 宽度和对齐
std::cout << std::format("|{:>10}|\n", 42); // 右对齐
std::cout << std::format("|{:<10}|\n", 42); // 左对齐
std::cout << std::format("|{:^10}|\n", 42); // 居中
// 填充字符
std::cout << std::format("|{:*^10}|\n", 42); // 居中用*填充
}
输出到迭代器和缓冲区
#include <format>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
// format_to——输出到迭代器
std::string buf;
std::format_to(std::back_inserter(buf), "{} + {} = {}", 2, 3, 5);
std::cout << buf << '\n'; // 输出: 2 + 3 = 5
// format_to_n——限制输出大小
char buf2[10]{};
auto result = std::format_to_n(buf2, 9, "{}-{}", "abc", "def");
std::cout << buf2 << '\n'; // 输出: abc-def
}
自定义类型的formatter特化
#include <format>
#include <iostream>
struct Point {
int x, y;
};
// 特化formatter以支持自定义类型
template<>
struct std::formatter<Point> {
constexpr auto parse(std::format_parse_context& ctx) {
return ctx.begin();
}
auto format(const Point& p, std::format_context& ctx) const {
return std::format_to(ctx.out(), "Point({}, {})", p.x, p.y);
}
};
int main() {
Point p{3, 4};
std::cout << std::format("{}\n", p); // 输出: Point(3, 4)
}
常用格式说明符
| 说明符 | 含义 | 示例 |
|---|---|---|
{} |
默认格式 | format("{}", 42) → "42" |
{:.2f} |
浮点数保留2位小数 | format("{:.2f}", 3.14159) → "3.14" |
{:>10} |
右对齐,宽度10 | format("{:>10}", 42) → " 42" |
{:<10} |
左对齐,宽度10 | format("{:<10}", 42) → "42 " |
{:^10} |
居中,宽度10 | format("{:^10}", 42) → " 42 " |
{:*^10} |
用*填充居中 | format("{:*^10}", 42) → "****42****" |
{:b} |
二进制输出 | format("{:b}", 42) → "101010" |
{:x} |
十六进制输出 | format("{:x}", 255) → "ff" |
{:X} |
大写十六进制 | format("{:X}", 255) → "FF" |
{:#x} |
带前缀十六进制 | format("{:#x}", 255) → "0xff" |
1.2 constexpr容器 —— 编译时vector和string
背景
C++20允许在编译时使用 std::vector 和 std::string,这意味着可以在编译期构造、修改和销毁动态容器。
编译时vector
#include <vector>
#include <algorithm>
constexpr int sum_vec() {
std::vector<int> v{1, 2, 3, 4, 5};
v.push_back(6);
int sum = 0;
for (int x : v) sum += x;
return sum;
}
int main() {
constexpr int result = sum_vec();
// result == 21, 在编译期计算
static_assert(result == 21);
return result;
}
编译时string
#include <string>
constexpr std::string make_greeting() {
std::string s = "Hello";
s += ", ";
s += "World!";
return s;
}
int main() {
constexpr std::string greeting = make_greeting();
static_assert(greeting.size() == 13);
static_assert(greeting == "Hello, World!");
return 0;
}
编译时排序
#include <vector>
#include <algorithm>
constexpr std::vector<int> sort_vec() {
std::vector<int> v{5, 2, 8, 1, 9, 4};
std::sort(v.begin(), v.end());
return v;
}
int main() {
constexpr auto sorted = sort_vec();
static_assert(sorted[0] == 1);
static_assert(sorted[5] == 9);
return 0;
}
注意事项
- 编译时分配的内存必须在编译时释放
- 不能在运行时使用编译期构造的容器(它们会在编译结束后被销毁)
- constexpr容器不能包含非平凡析构的类型
1.3 安全比较不同类型的整数 —— cmp_less 等
背景
传统的有符号和无符号整数比较可能导致意外行为。C++20引入了安全的整数比较函数。
问题示例
#include <iostream>
int main() {
int x = -1;
unsigned int y = 1;
// 传统比较的陷阱!
if (x < y) {
std::cout << "x < y\n"; // 不会执行!因为x被隐式转换为unsigned
} else {
std::cout << "x > y\n"; // 会执行这个!
}
// x被转换为unsigned(-1) = 4294967295 > 1
}
安全比较函数
#include <utility>
#include <iostream>
int main() {
int x = -1;
unsigned int y = 1;
// 安全的比较
if (std::cmp_less(x, y)) { // -1 < 1,true
std::cout << "x < y\n";
}
if (std::cmp_greater(y, x)) { // 1 > -1,true
std::cout << "y > x\n";
}
}
完整的安全比较函数族
| 函数 | 等价于 |
|---|---|
std::cmp_equal(x, y) |
x == y |
std::cmp_not_equal(x, y) |
x != y |
std::cmp_less(x, y) |
x < y |
std::cmp_greater(x, y) |
x > y |
std::cmp_less_equal(x, y) |
x <= y |
std::cmp_greater_equal(x, y) |
x >= y |
1.4 三路比较运算符 <=> —— "太空船运算符"
背景
C++20引入了三路比较运算符 <=>,可以一次性返回小于、等于或大于三种结果。结合 = default 可以自动生成所有比较运算符。
基本用法
#include <compare>
#include <iostream>
int main() {
int a = 3, b = 5;
auto result = a <=> b;
if (result < 0) std::cout << "a < b\n";
if (result == 0) std::cout << "a == b\n";
if (result > 0) std::cout << "a > b\n";
}
比较类别
#include <compare>
// std::strong_ordering: less, equal, greater, equivalent
// std::weak_ordering: less, equivalent, greater
// std::partial_ordering: less, equivalent, greater, unordered
std::strong_ordering s = 1 <=> 2; // strong_ordering::less
double nan = std::numeric_limits<double>::quiet_NaN();
std::partial_ordering p = nan <=> 1.0; // partial_ordering::unordered
自动生成比较运算符
#include <compare>
#include <iostream>
struct Point {
int x, y;
// 一行代码自动生成 ==, !=, <, <=, >, >=
auto operator<=>(const Point&) const = default;
};
int main() {
Point p1{1, 2}, p2{1, 3}, p3{1, 2};
std::cout << std::boolalpha;
std::cout << (p1 < p2) << '\n'; // true (先比较x,再比较y)
std::cout << (p1 == p3) << '\n'; // true
std::cout << (p2 > p1) << '\n'; // true
}
自定义三路比较
#include <compare>
#include <string>
struct Person {
std::string name;
int age;
// 自定义比较:按年龄排序
std::strong_ordering operator<=>(const Person& other) const {
return age <=> other.age;
}
// 还需要定义 == 运算符
bool operator==(const Person& other) const = default;
};
1.5 查找特性测试宏 —— <version> 头文件
背景
<version> 头文件包含了所有C++标准库的特性测试宏,用于在编译时确定编译器支持哪些特性。
基本用法
#include <version>
#include <iostream>
int main() {
// 检查是否有 <format> 头文件
#ifdef __cpp_lib_format
std::cout << "支持 std::format\n";
#else
std::cout << "不支持 std::format\n";
#endif
// 检查是否有 constexpr vector
#ifdef __cpp_lib_constexpr_vector
std::cout << "支持 constexpr vector\n";
#endif
// 检查是否有三路比较
#ifdef __cpp_lib_three_way_comparison
std::cout << "支持三路比较\n";
#endif
// 检查span
#ifdef __cpp_lib_span
std::cout << "支持 std::span\n";
#endif
}
常用特性测试宏
| 宏 | 特性 |
|---|---|
__cpp_lib_format |
std::format格式化库 |
__cpp_lib_constexpr_vector |
constexpr vector |
__cpp_lib_three_way_comparison |
<=> 三路比较 |
__cpp_lib_concepts |
概念与约束 |
__cpp_lib_span |
std::span |
__cpp_lib_ranges |
ranges范围库 |
__cpp_lib_string_view |
std::string_view |
__cpp_lib_optional |
std::optional |
__cpp_lib_variant |
std::variant |
__cpp_lib_any |
std::any |
__cpp_lib_parallel_algorithm |
并行算法 |
__cpp_lib_smart_ptr_for_overwrite |
make_unique_for_overwrite |
1.6 概念(Concept)和约束(Constraint) —— 创建更安全的模板
背景
概念和约束是C++20最重要的语言特性之一,它允许对模板参数施加编译期约束,提供更清晰的错误信息和更好的重载解析。
定义概念
#include <concepts>
#include <iostream>
// 定义一个概念:要求类型可以哈希
template<typename T>
concept Hashable = requires(T a) {
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
// 定义一个概念:要求类型可相等比较
template<typename T>
concept EqualityComparable = requires(T a, T b) {
{ a == b } -> std::convertible_to<bool>;
{ a != b } -> std::convertible_to<bool>;
};
// 组合概念
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
使用概念约束模板
#include <concepts>
#include <iostream>
// 方式1:requires子句
template<typename T>
requires Numeric<T>
T add(T a, T b) {
return a + b;
}
// 方式2:概念名代替typename
template<Numeric T>
T multiply(T a, T b) {
return a * b;
}
// 方式3:简写语法
auto subtract(Numeric auto a, Numeric auto b) {
return a - b;
}
int main() {
std::cout << add(3, 4) << '\n'; // 7
std::cout << multiply(3.5, 2.0) << '\n'; // 7.0
// add("hello", "world"); // 编译错误:const char* 不满足 Numeric
}
requires表达式
#include <concepts>
#include <vector>
// 检查类型是否有size()方法且返回可转为size_t
template<typename T>
concept Sized = requires(T t) {
{ t.size() } -> std::convertible_to<std::size_t>;
};
// 检查类型是否可迭代
template<typename T>
concept Iterable = requires(T t) {
typename T::iterator;
{ t.begin() } -> std::same_as<typename T::iterator>;
{ t.end() } -> std::same_as<typename T::iterator>;
};
template<Iterable T>
void print_first(const T& container) {
if (container.begin() != container.end()) {
// ...
}
}
标准库中的概念
#include <concepts>
// 类型分类概念
std::integral<int>; // true
std::floating_point<double>; // true
std::signed_integral<int>; // true
std::unsigned_integral<unsigned>; // true
// 移动和复制概念
std::movable<std::string>; // true
std::copyable<std::string>; // true
// 可调用概念
std::invocable<int(int,int)>; // 可作为 int(int,int) 调用
// 关系概念
std::equality_comparable<int>; // true
std::totally_ordered<std::string>; // true
1.7 模块(Module) —— 避免重复编译模板库
背景
C++20引入了模块系统,旨在替换传统的头文件包含机制,大幅提升编译速度,特别是对于模板库。
基础模块定义
// math_module.ixx —— 模块接口文件
export module math;
export namespace math {
auto add(auto a, auto b) { return a + b; }
auto subtract(auto a, auto b) { return a - b; }
constexpr double PI = 3.14159265358979;
}
导入和使用模块
// main.cpp
import math;
#include <iostream>
int main() {
std::cout << math::add(3, 4) << '\n'; // 7
std::cout << math::subtract(10, 3) << '\n'; // 7
std::cout << math::PI << '\n'; // 3.14159...
}
模块分区
// math.ixx —— 主模块接口
export module math;
export import :arithmetic; // 导出算术分区
export import :trig; // 导出三角分区
// math-arithmetic.ixx —— 算术分区
export module math:arithmetic;
export namespace math {
auto pow2(auto x) { return x * x; }
auto sum(auto... args) { return (args + ...); }
}
// math-trig.ixx —— 三角分区
export module math:trig;
export namespace math {
constexpr double PI = 3.14159265358979;
double sin(double x);
}
全局模块片段
// 用于在模块中包含传统的头文件
module;
#include <vector>
#include <string>
export module my_module;
export class MyClass {
std::vector<std::string> data;
public:
void add(const std::string& s) { data.push_back(s); }
};
1.8 范围(Ranges) —— 在容器上创建视图
背景
C++20的范围库提供了处理元素范围的全新方式,通过视图(View)实现了惰性求值的管道式操作。
ranges基本用法
#include <ranges>
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// ranges版本的sort
std::ranges::sort(v, std::ranges::greater{});
// ranges版本的find
auto it = std::ranges::find(v, 5);
if (it != v.end()) {
std::cout << "找到: " << *it << '\n';
}
}
视图(Views)和管道操作
#include <ranges>
#include <vector>
#include <iostream>
int main() {
namespace views = std::views;
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 管道操作:过滤 + 变换
auto result = v
| views::filter([](int x) { return x % 2 == 0; }) // 保留偶数
| views::transform([](int x) { return x * x; }) // 平方
| views::take(3); // 取前3个
for (int x : result) {
std::cout << x << ' '; // 输出: 4 16 36
}
std::cout << '\n';
}
常用视图
#include <ranges>
#include <vector>
#include <iostream>
int main() {
namespace views = std::views;
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// filter:过滤元素
auto evens = v | views::filter([](int x) { return x % 2 == 0; });
// transform:变换元素
auto squares = v | views::transform([](int x) { return x * x; });
// take:取前n个
auto first5 = v | views::take(5);
// drop:跳过前n个
auto after5 = v | views::drop(5);
// reverse:反转
auto reversed = v | views::reverse;
// 组合使用
auto pipeline = v
| views::filter([](int x) { return x > 3; })
| views::transform([](int x) { return x * 2; })
| views::take(4);
for (int x : pipeline) {
std::cout << x << ' '; // 输出: 8 10 12 14
}
// iota:生成序列
for (int x : views::iota(1, 11)) {
std::cout << x << ' '; // 输出: 1 2 3 4 5 6 7 8 9 10
}
}
范围适配器
| 视图 | 功能 |
|---|---|
views::filter(pred) |
过滤满足谓词的元素 |
views::transform(fn) |
对每个元素应用变换函数 |
views::take(n) |
取前n个元素 |
views::drop(n) |
跳过前n个元素 |
views::reverse |
反转元素顺序 |
views::join |
扁平化嵌套范围 |
views::split(delim) |
按分隔符拆分 |
views::iota(start, end) |
生成整数序列 |
views::common |
将range转为common_range |
views::all |
将容器转为视图 |
本章小结
本章介绍了C++20中与STL密切相关的八大新特性:
- std::format —— 类型安全、高效的字符串格式化
- constexpr容器 —— 编译期vector和string
- 安全整数比较 ——
cmp_less等函数族 - 三路比较 ——
<=>运算符自动生成比较 - 特性测试宏 ——
<version>头文件 - 概念与约束 —— 模板参数的类型安全约束
- 模块 —— 替代头文件的现代编译模型
- 范围库 —— 惰性求值的管道式数据处理
这些特性共同构成了现代C++编程的基础设施,后续章节将深入运用这些技术。