通用工具库
第 22 章导读:<utility>、pair、tuple、optional、variant、any、expected、bitset、<functional> 和 <bit> 各自解决什么问题,以及读这一章的条文前要先认识的 Constraints、Mandates、Preconditions 和 Hardened preconditions。
本节要点
- 第 22 章收录几乎每个程序都会用到、又不属于容器、算法或 I/O 的小组件,其中不少还是标准库其他部分的积木,例如
std::move、std::pair、std::invoke。 optional、variant、any、expected都是在一个对象里存放可能不同的值;前两者和expected不分配内存,特殊成员函数随元素类型有条件地平凡。- 库函数的说明分成固定的几个元素:违反 Constraints 时该函数退出重载决议,违反 Mandates 时编译报错,违反 Preconditions 是未定义行为。
- C++26 把
optional::operator*等不检查的访问改成了 Hardened preconditions:在加固实现中违反时程序终止,在其他实现中仍是未定义行为。
本章地图 [utilities.general]#
¶1 本章描述在 C++ 程序中普遍有用的工具,其中一些也被标准库的其他部分使用。
| 节 | 条款 | 头文件 | 内容 |
|---|---|---|---|
| 22.2 | [utility] | <utility> |
swap、exchange、move、forward、declval、整数安全比较 cmp_less 等、to_underlying、unreachable;C++26 constant_wrapper([const.wrap.class]) |
| 22.3 | [pairs] | <utility> |
pair |
| 22.4 | [tuple] | <tuple> |
tuple、apply、make_from_tuple |
| 22.5 | [optional] | <optional> |
可能为空的值 optional<T>;C++26 optional<T&> |
| 22.6 | [variant] | <variant> |
类型安全的联合体 variant、visit |
| 22.7 | [any] | <any> |
可以存放任意可复制类型的 any |
| 22.8 | [expected] | <expected> |
C++23 值或错误 expected<T, E> |
| 22.9 | [bitset] | <bitset> |
定长位集 |
| 22.10 | [function.objects] | <functional> |
INVOKE、reference_wrapper、bind_front、function、move_only_function、function_ref、hash 等 |
| 22.11 | [bit] | <bit> |
bit_cast、byteswap、2 的幂、循环移位、位计数 |
| 22.12 | [stdbit.h.syn] | <stdbit.h> |
C++26 C23 的位操作头文件 |
已经搬走的内容
C++17 和 C++20 的 [utilities] 还包括智能指针和内存工具、<type_traits>、<ratio>、<charconv>、<format>、执行策略、type_index 等(C++17 还有 <chrono>)。现在它们分散在别处:内存在 [mem],类型特征和 <ratio> 在 [meta],<charconv> 和 <format> 在 [text],执行策略在 [execpol],type_index 在 [type.index],时间库在 [time]。引用旧版标准的条款号时要注意这一点。
四种词汇类型#
optional、variant、any、expected 常被称为词汇类型(vocabulary types):不同的库用同一种类型表达同一件事,接口就能互相配合。它们的设计取舍可以放在一张表里比较:
optional<T> |
variant<Ts...> |
any |
expected<T, E> |
|
|---|---|---|---|---|
| 存什么 | 一个 T,或者没有值 |
Ts 中恰好一个 |
任意可复制的类型 | 一个 T,或者一个错误 E |
| 存储 | 对象内部 | 对象内部 | 可能在堆上(标准鼓励对小对象避免分配) | 对象内部 |
| 空状态 | nullopt,正常状态 |
valueless_by_exception(),只会因异常出现 |
空的 any,正常状态 |
没有:总是有值或有错误 |
| 访问错的东西 | operator* 违反加固前置条件;value() 抛 bad_optional_access |
get 抛 bad_variant_access;get_if 返回空指针 |
any_cast 抛 bad_any_cast 或返回空指针 |
operator* 违反加固前置条件;value() 抛 bad_expected_access<E> |
| 平凡性 | 特殊成员随 T 有条件地平凡 |
随全部 Ts |
不平凡 | 随 T 和 E |
最后一行值得多看一眼:
#include <optional>
#include <string>
#include <type_traits>
static_assert( std::is_trivially_copyable_v<std::optional<int>>);
static_assert(!std::is_trivially_copyable_v<std::optional<std::string>>);
int main() {}optional<int> 可以像 int 一样用 memcpy 复制、在寄存器里传递,optional<string> 不行。一个类模板要做到这一点,需要两方面的语言支持:联合体的特殊成员只有在所有变体成员的对应函数都平凡时才不被弃置([class.union]);C++20 起一个类可以声明多个带不同约束的预期析构函数等特殊成员,由约束选出其中一个([class.dtor]、[special])。细节见 [optional.optional] 和 [variant.variant],平凡性为什么重要见 [class.prop]。
读库条文要先认识的元素#
库条文中每个函数都按 [structure.specifications]/3 规定的元素书写。不同元素被违反时,后果完全不同:
| 元素 | 不满足时 |
|---|---|
| Constraints | 该函数不参与重载决议,不报错,可以被 requires 表达式探测到 |
| Mandates | 程序非良构,编译器必须诊断 |
| Constant When | 这次调用不是常量子表达式 |
| Preconditions | 未定义行为 |
| Hardened preconditions | 加固实现在函数产生其他可观察副作用之前检查条件,失败时终止;其他实现中是未定义行为 |
#include <variant>
int main() {
std::variant<int, int> v{std::in_place_index<0>, 1};
return std::get<int>(v); // error: int 在 Ts 中出现了两次,违反 Mandates
}std::get<T>(variant) 要求 T 在 Ts... 中恰好出现一次,这是 Mandates,违反时直接编译失败,不会退而选择别的重载。按下标取值的 std::get<0>(v) 没有这个问题。反过来,optional<T> 的转换构造函数用的是 Constraints:条件不满足时这个构造函数只是退出重载决议,is_constructible_v<optional<int>, std::string> 平静地得到 false。判断一个库接口能否用于概念检测,看的就是这个区别。
加固前置条件 C++26#
#include <optional>
int main() {
std::optional<int> o;
return *o; // 违反 hardened precondition:has_value() 为 false
}optional::operator*、expected::operator->、bitset::operator[] 等不检查的访问函数,过去是普通前置条件,违反就是未定义行为。C++26 把它们改成了加固前置条件:同一份代码,在加固的标准库下运行到这里会确定地终止。本机 libc++ 用 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST 编译上面的程序,运行时以 SIGTRAP 终止;不加这个宏则没有任何检查。哪些实现算加固实现见 [intro.compliance]。
另一个常见措辞是 Equivalent to:Effects 写成等价于某段代码时,那段代码的语义(调用哪些函数、抛出什么异常、能否用于常量求值)就是这个函数的语义([structure.specifications]/4)。std::apply、optional::value_or、expected 的 and_then 等都这样定义。
推荐阅读顺序#
- [utility]:
move、forward、declval是阅读其余条文的基础词汇。 - [func.require]:INVOKE 的定义,
apply、visit、function、optional::and_then都以它为基础。 - [pairs] 和 [tuple]:类元组协议,以及它和结构化绑定([dcl.struct.bind])的关系。
- [optional.optional]、[variant.variant]、[expected.expected]:同一套有条件平凡的技巧用了三次;[any] 是类型擦除的对照。
- [func.wrap]:四种多态函数包装器的取舍。
- [bit]:
bit_cast是合法地重新解释对象表示的标准做法,可与 [basic.lval] 的别名规则对照阅读。
思考题#
思考题
std::optional<int> 是平凡可复制的吗?标准在哪里保证了这一点?
答案
是。[optional.ctor] 规定,若 is_trivially_copy_constructible_v<T> 为真,复制构造函数是平凡的;移动构造、复制赋值、移动赋值和析构函数([optional.dtor])都有类似的条款。int 满足全部条件,于是 optional<int> 满足 [class.prop] 对平凡可复制类的定义。std::string 的复制构造和析构都不平凡,所以 optional<std::string> 不是平凡可复制的。
条款一览
- 22.1General 概述[utilities.general]
- 22.2Utility components 工具组件[utility]完成
- 22.2.1Header <utility> synopsis 头文件 <utility> 概要[utility.syn]
- 22.2.2swap swap[utility.swap]
- 22.2.3exchange exchange[utility.exchange]
- 22.2.4Forward/move helpers forward/move 辅助函数[forward]
- 22.2.5Function template as_const 函数模板 as_const[utility.as.const]
- 22.2.6Function template declval 函数模板 declval[declval]
- 22.2.7Integer comparison functions 整数比较函数[utility.intcmp]
- 22.2.8Function template to_underlying 函数模板 to_underlying[utility.underlying]
- 22.2.9Undefined behavior 未定义行为[utility.undefined]
- 22.2.10Class template constant_wrapper 类模板 constant_wrapper[const.wrap.class]完成
- 22.3Pairs 对(pair)[pairs]完成
- 22.4Tuples 元组[tuple]完成
- 22.4.1General 概述[tuple.general]
- 22.4.2Header <tuple> synopsis 头文件 <tuple> 概要[tuple.syn]
- 22.4.3Concept tuple-like 概念 tuple-like[tuple.like]
- 22.4.4Class template tuple 类模板 tuple[tuple.tuple]
- 22.4.5Tuple creation functions 元组创建函数[tuple.creation]
- 22.4.6Calling a function with a tuple of arguments 以元组为实参调用函数[tuple.apply]
- 22.4.7Tuple helper classes 元组辅助类[tuple.helper]
- 22.4.8Element access 元素访问[tuple.elem]
- 22.4.9Relational operators 关系运算符[tuple.rel]
- 22.4.10common_reference related specializations common_reference 相关特化[tuple.common.ref]
- 22.4.11Tuple traits 元组特征[tuple.traits]
- 22.4.12Tuple specialized algorithms 元组特化的算法[tuple.special]
- 22.5Optional objects 可选对象[optional]完成
- 22.5.1General 概述[optional.general]
- 22.5.2Header <optional> synopsis 头文件 <optional> 概要[optional.syn]
- 22.5.3Class template optional 类模板 optional[optional.optional]草稿
- 22.5.3.1General 概述[optional.optional.general]
- 22.5.3.2Constructors 构造函数[optional.ctor]
- 22.5.3.3Destructor 析构函数[optional.dtor]
- 22.5.3.4Assignment 赋值[optional.assign]
- 22.5.3.5Swap 交换[optional.swap]
- 22.5.3.6Iterator support 迭代器支持[optional.iterators]
- 22.5.3.7Observers 观察器[optional.observe]
- 22.5.3.8Monadic operations 单子操作[optional.monadic]
- 22.5.3.9Modifiers 修改器[optional.mod]
- 22.5.4Partial specialization of optional for reference types optional 针对引用类型的部分特化[optional.optional.ref]草稿
- 22.5.4.1General 概述[optional.optional.ref.general]
- 22.5.4.2Constructors 构造函数[optional.ref.ctor]
- 22.5.4.3Assignment 赋值[optional.ref.assign]
- 22.5.4.4Swap 交换[optional.ref.swap]
- 22.5.4.5Iterator support 迭代器支持[optional.ref.iterators]
- 22.5.4.6Observers 观察器[optional.ref.observe]
- 22.5.4.7Monadic operations 单子操作[optional.ref.monadic]
- 22.5.4.8Modifiers 修改器[optional.ref.mod]
- 22.5.4.9Exposition only helper functions 仅用于阐述的辅助函数[optional.ref.expos]
- 22.5.5No-value state indicator 无值状态指示器[optional.nullopt]
- 22.5.6Class bad_optional_access 类 bad_optional_access[optional.bad.access]
- 22.5.7Relational operators 关系运算符[optional.relops]
- 22.5.8Comparison with nullopt 与 nullopt 比较[optional.nullops]
- 22.5.9Comparison with T 与 T 比较[optional.comp.with.t]
- 22.5.10Specialized algorithms 特化的算法[optional.specalg]
- 22.5.11Hash support 散列支持[optional.hash]
- 22.6Variants 变体[variant]完成
- 22.6.1General 概述[variant.general]
- 22.6.2Header <variant> synopsis 头文件 <variant> 概要[variant.syn]
- 22.6.3Class template variant 类模板 variant[variant.variant]完成
- 22.6.4variant helper classes variant 辅助类[variant.helper]
- 22.6.5Value access 值访问[variant.get]
- 22.6.6Relational operators 关系运算符[variant.relops]
- 22.6.7Visitation 访问(visit)[variant.visit]完成
- 22.6.8Class monostate 类 monostate[variant.monostate]
- 22.6.9monostate relational operators monostate 关系运算符[variant.monostate.relops]
- 22.6.10Specialized algorithms 特化的算法[variant.specalg]
- 22.6.11Class bad_variant_access 类 bad_variant_access[variant.bad.access]
- 22.6.12Hash support 散列支持[variant.hash]
- 22.7Storage for any type 任意类型的存储[any]完成
- 22.8Expected objects expected 对象[expected]草稿
- 22.8.1General 概述[expected.general]
- 22.8.2Header <expected> synopsis 头文件 <expected> 概要[expected.syn]
- 22.8.3Class template unexpected 类模板 unexpected[expected.unexpected]
- 22.8.4Class template bad_expected_access 类模板 bad_expected_access[expected.bad]
- 22.8.5Class template specialization bad_expected_access<void> 类模板特化 bad_expected_access<void>[expected.bad.void]
- 22.8.6Class template expected 类模板 expected[expected.expected]草稿
- 22.8.6.1General 概述[expected.object.general]
- 22.8.6.2Constructors 构造函数[expected.object.cons]
- 22.8.6.3Destructor 析构函数[expected.object.dtor]
- 22.8.6.4Assignment 赋值[expected.object.assign]
- 22.8.6.5Swap 交换[expected.object.swap]
- 22.8.6.6Observers 观察器[expected.object.obs]
- 22.8.6.7Monadic operations 单子操作[expected.object.monadic]
- 22.8.6.8Equality operators 相等性运算符[expected.object.eq]
- 22.8.7Partial specialization of expected for void types expected 针对 void 类型的部分特化[expected.void]草稿
- 22.8.7.1General 概述[expected.void.general]
- 22.8.7.2Constructors 构造函数[expected.void.cons]
- 22.8.7.3Destructor 析构函数[expected.void.dtor]
- 22.8.7.4Assignment 赋值[expected.void.assign]
- 22.8.7.5Swap 交换[expected.void.swap]
- 22.8.7.6Observers 观察器[expected.void.obs]
- 22.8.7.7Monadic operations 单子操作[expected.void.monadic]
- 22.8.7.8Equality operators 相等性运算符[expected.void.eq]
- 22.9Bitsets 位集[bitset]草稿
- 22.10Function objects 函数对象[function.objects]完成
- 22.10.1General 概述[function.objects.general]
- 22.10.2Header <functional> synopsis 头文件 <functional> 概要[functional.syn]
- 22.10.3Definitions 定义[func.def]
- 22.10.4Requirements 要求[func.require]完成
- 22.10.5invoke functions invoke 函数[func.invoke]
- 22.10.6Class template reference_wrapper 类模板 reference_wrapper[refwrap]完成
- 22.10.6.1General 概述[refwrap.general]
- 22.10.6.2Constructors 构造函数[refwrap.const]
- 22.10.6.3Assignment 赋值[refwrap.assign]
- 22.10.6.4Access 访问[refwrap.access]
- 22.10.6.5Invocation 调用[refwrap.invoke]
- 22.10.6.6Comparisons 比较[refwrap.comparisons]
- 22.10.6.7Helper functions 辅助函数[refwrap.helpers]
- 22.10.6.8common_reference related specializations common_reference 相关特化[refwrap.common.ref]
- 22.10.7Arithmetic operations 算术运算[arithmetic.operations]
- 22.10.7.1General 概述[arithmetic.operations.general]
- 22.10.7.2Class template plus 类模板 plus[arithmetic.operations.plus]
- 22.10.7.3Class template minus 类模板 minus[arithmetic.operations.minus]
- 22.10.7.4Class template multiplies 类模板 multiplies[arithmetic.operations.multiplies]
- 22.10.7.5Class template divides 类模板 divides[arithmetic.operations.divides]
- 22.10.7.6Class template modulus 类模板 modulus[arithmetic.operations.modulus]
- 22.10.7.7Class template negate 类模板 negate[arithmetic.operations.negate]
- 22.10.8Comparisons 比较[comparisons]
- 22.10.8.1General 概述[comparisons.general]
- 22.10.8.2Class template equal_to 类模板 equal_to[comparisons.equal.to]
- 22.10.8.3Class template not_equal_to 类模板 not_equal_to[comparisons.not.equal.to]
- 22.10.8.4Class template greater 类模板 greater[comparisons.greater]
- 22.10.8.5Class template less 类模板 less[comparisons.less]
- 22.10.8.6Class template greater_equal 类模板 greater_equal[comparisons.greater.equal]
- 22.10.8.7Class template less_equal 类模板 less_equal[comparisons.less.equal]
- 22.10.8.8Class compare_three_way 类 compare_three_way[comparisons.three.way]
- 22.10.9Concept-constrained comparisons 概念约束的比较[range.cmp]
- 22.10.10Logical operations 逻辑运算[logical.operations]
- 22.10.11Bitwise operations 位运算[bitwise.operations]
- 22.10.11.1General 概述[bitwise.operations.general]
- 22.10.11.2Class template bit_and 类模板 bit_and[bitwise.operations.and]
- 22.10.11.3Class template bit_or 类模板 bit_or[bitwise.operations.or]
- 22.10.11.4Class template bit_xor 类模板 bit_xor[bitwise.operations.xor]
- 22.10.11.5Class template bit_not 类模板 bit_not[bitwise.operations.not]
- 22.10.12Class identity 类 identity[func.identity]
- 22.10.13Function template not_fn 函数模板 not_fn[func.not.fn]完成
- 22.10.14Function templates bind_front and bind_back 函数模板 bind_front 与 bind_back[func.bind.partial]完成
- 22.10.15Function object binders 函数对象绑定器[func.bind]完成
- 22.10.15.1General 概述[func.bind.general]
- 22.10.15.2Class template is_bind_expression 类模板 is_bind_expression[func.bind.isbind]
- 22.10.15.3Class template is_placeholder 类模板 is_placeholder[func.bind.isplace]
- 22.10.15.4Function template bind 函数模板 bind[func.bind.bind]
- 22.10.15.5Placeholders 占位符[func.bind.place]
- 22.10.16Function template mem_fn 函数模板 mem_fn[func.memfn]完成
- 22.10.17Polymorphic function wrappers 多态函数包装器[func.wrap]完成
- 22.10.17.1General 概述[func.wrap.general]
- 22.10.17.2Class bad_function_call 类 bad_function_call[func.wrap.badcall]
- 22.10.17.3Class template function 类模板 function[func.wrap.func]完成
- 22.10.17.3.1General 概述[func.wrap.func.general]
- 22.10.17.3.2Constructors and destructor 构造函数与析构函数[func.wrap.func.con]
- 22.10.17.3.3Modifiers 修改器[func.wrap.func.mod]
- 22.10.17.3.4Capacity 容量[func.wrap.func.cap]
- 22.10.17.3.5Invocation 调用[func.wrap.func.inv]
- 22.10.17.3.6Target access 目标访问[func.wrap.func.targ]
- 22.10.17.3.7Null pointer comparison operator functions 空指针比较运算符函数[func.wrap.func.nullptr]
- 22.10.17.3.8Specialized algorithms 特化的算法[func.wrap.func.alg]
- 22.10.17.4Move-only wrapper 仅移动包装器[func.wrap.move]草稿
- 22.10.17.4.1General 概述[func.wrap.move.general]
- 22.10.17.4.2Class template move_only_function 类模板 move_only_function[func.wrap.move.class]
- 22.10.17.4.3Constructors, assignments, and destructor 构造函数、赋值与析构函数[func.wrap.move.ctor]
- 22.10.17.4.4Invocation 调用[func.wrap.move.inv]
- 22.10.17.4.5Utility 工具[func.wrap.move.util]
- 22.10.17.5Copyable wrapper 可复制包装器[func.wrap.copy]草稿
- 22.10.17.5.1General 概述[func.wrap.copy.general]
- 22.10.17.5.2Class template copyable_function 类模板 copyable_function[func.wrap.copy.class]
- 22.10.17.5.3Constructors, assignments, and destructor 构造函数、赋值与析构函数[func.wrap.copy.ctor]
- 22.10.17.5.4Invocation 调用[func.wrap.copy.inv]
- 22.10.17.5.5Utility 工具[func.wrap.copy.util]
- 22.10.17.6Non-owning wrapper 非拥有包装器[func.wrap.ref]草稿
- 22.10.17.6.1General 概述[func.wrap.ref.general]
- 22.10.17.6.2Class template function_ref 类模板 function_ref[func.wrap.ref.class]
- 22.10.17.6.3Constructors and assignment operators 构造函数与赋值运算符[func.wrap.ref.ctor]
- 22.10.17.6.4Invocation 调用[func.wrap.ref.inv]
- 22.10.17.6.5Deduction guides 推导指引[func.wrap.ref.deduct]
- 22.10.18Searchers 搜索器[func.search]完成
- 22.10.18.1General 概述[func.search.general]
- 22.10.18.2Class template default_searcher 类模板 default_searcher[func.search.default]
- 22.10.18.3Class template boyer_moore_searcher 类模板 boyer_moore_searcher[func.search.bm]
- 22.10.18.4Class template boyer_moore_horspool_searcher 类模板 boyer_moore_horspool_searcher[func.search.bmh]
- 22.10.19Class template hash 类模板 hash[unord.hash]完成
- 22.11Bit manipulation 位操作[bit]草稿
- 22.11.1General 概述[bit.general]
- 22.11.2Header <bit> synopsis 头文件 <bit> 概要[bit.syn]
- 22.11.3Function template bit_cast 函数模板 bit_cast[bit.cast]
- 22.11.4byteswap byteswap[bit.byteswap]
- 22.11.5Integral powers of 2 2 的整数次幂[bit.pow.two]
- 22.11.6Shifting 移位[bit.shift]
- 22.11.7Rotating 循环移位[bit.rotate]
- 22.11.8Counting 计数[bit.count]
- 22.11.9Permutation 置换[bit.permute]
- 22.11.10Endian 字节序[bit.endian]
- 22.12Header <stdbit.h> synopsis 头文件 <stdbit.h> 概要[stdbit.h.syn]草稿