swap(std::expected)
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::expected
swap(std::expected)
friend constexpr void swap( expected& lhs, expected& rhs ) noexcept(/*see below*/);
(since C++23)
Overloads the std::swap algorithm for std::expected. Exchanges the state of lhs with that of rhs. Effectively calls lhs.swap(rhs).
This overload participates in overload resolution only if lhs.swap(rhs) is valid.
This function is not visible to ordinary unqualified or qualified lookup, and can only be found by argument-dependent lookup when std::expected <T, E> is an associated class of the arguments.
[edit] Parameters
lhs, rhs
-
expected
objects whose states to swap
[edit] Return value
(none)
[edit] Exceptions
noexcept specification:
noexcept(noexcept(lhs.swap(rhs)))
[edit] Example
Run this code
#include <expected> #include <iostream> #include <string_view> using Ex = std::expected <std::string, int>; void show(const Ex& ex1, const Ex& ex2, std::string_view term = "\n") { for (int i{}; i != 2; ++i) { std::cout << (i ? "ex2" : "ex1"); if (const Ex& ex = (i ? ex2 : ex1); ex.has_value()) std::cout << ".value() = " << *ex << " "; else std::cout << ".error() = " << ex.error() << " "; } std::cout << term; } int main() { Ex ex1("\N{SMILING FACE WITH SUNGLASSES}"); Ex ex2{"\N{SLIGHTLY SMILING FACE}"}; show(ex1, ex2, "after swap(ex1, ex2):\n"); std::swap (ex1, ex2); show(ex1, ex2, "\n\n"); ex2 = std::unexpected (13); show(ex1, ex2, "after swap(ex1, ex2):\n"); std::swap (ex1, ex2); show(ex1, ex2, "\n\n"); ex2 = std::unexpected (37); show(ex1, ex2, "after swap(ex1, ex2):\n"); std::swap (ex1, ex2); show(ex1, ex2); }
Output:
ex1.value() = 😎 ex2.value() = 🙂 after swap(ex1, ex2): ex1.value() = 🙂 ex2.value() = 😎 ex1.value() = 🙂 ex2.error() = 13 after swap(ex1, ex2): ex1.error() = 13 ex2.value() = 🙂 ex1.error() = 13 ex2.error() = 37 after swap(ex1, ex2): ex1.error() = 37 ex2.error() = 13