swap(std::expected)
来自 cppreference.cn
friend constexpr void swap( expected& lhs, expected& rhs ) noexcept(/*见下方*/); |
(自 C++23 起) | |
为 std::expected 重载 std::swap 算法。 交换 lhs 与 rhs 的状态。 有效地调用 lhs.swap(rhs)。
仅当 lhs.swap(rhs) 有效时,此重载才参与重载决议。
此函数对于普通的非限定或限定查找不可见,并且仅当 std::expected<T, E> 是参数的关联类时,才能通过实参依赖查找找到。
目录 |
[edit] 参数
lhs, rhs | - | 状态要交换的 expected 对象 |
[edit] 返回值
(无)
[edit] 异常
noexcept 规范:
noexcept(noexcept(lhs.swap(rhs)))
[edit] 示例
运行此代码
#include <expected> #include <iostream> #include <string> using Ex = std::expected<std::string, int>; void show(const Ex& ex1, const Ex& ex2) { for (int i{}; i < 2; ++i) { std::cout << (i ? "ex2" : "ex1"); if (const Ex& ex = (i ? ex2 : ex1); ex.has_value()) std::cout << ".has_value() = " << *ex << '\n'; else std::cout << ".error() = " << ex.error() << '\n'; } } int main() { Ex ex1("\N{DOG FACE}"); Ex ex2{"\N{BONE}"}; show(ex1, ex2); swap(ex1, ex2); std::cout << "swap(ex1, ex2);\n"; show(ex1, ex2); std::cout << '\n'; ex2 = std::unexpected(13); show(ex1, ex2); swap(ex1, ex2); std::cout << "swap(ex1, ex2);\n"; show(ex1, ex2); std::cout << '\n'; ex2 = std::unexpected(19937); show(ex1, ex2); swap(ex1, ex2); std::cout << "swap(ex1, ex2);\n"; show(ex1, ex2); std::cout << '\n'; }
输出
ex1.has_value() = 🐶 ex2.has_value() = 🦴 swap(ex1, ex2); ex1.has_value() = 🦴 ex2.has_value() = 🐶 ex1.has_value() = 🦴 ex2.error() = 13 swap(ex1, ex2); ex1.error() = 13 ex2.has_value() = 🦴 ex1.error() = 13 ex2.error() = 19937 swap(ex1, ex2); ex1.error() = 19937 ex2.error() = 13
[edit] 参见
交换内容 (公共成员函数) |