swap(std::expected)
来自cppreference.com
friendconstexprvoid swap( expected& lhs, expected& rhs )noexcept(/* 见下文 */); | (C++23 起) | |
为 std::expected 重载的 std::swap 算法。交换 lhs 与 rhs 的状态。等价于 lhs.swap(rhs)。
此重载只有在 lhs.swap(rhs) 合法时才会参与重载决议。
此函数对常规的无限定或有限定查找不可见,而只能在 std::expected<T, E> 为实参的关联类时由实参依赖查找找到。
目录 |
[编辑]参数
lhs, rhs | - | 要交换状态的 expected 对象 |
[编辑]返回值
(无)
[编辑]异常
noexcept 说明:
noexcept(noexcept(lhs.swap(rhs)))
[编辑]示例
运行此代码
#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';elsestd::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
[编辑]参阅
交换内容 (公开成员函数) |