std::expected<T,E>::swap - cppreference.com (original) (raw)

Primary template
constexpr void swap( expected& other ) noexcept(/* see below */); (1) (since C++23)
void partial specialization
constexpr void swap( expected& other ) noexcept(/* see below */); (2) (since C++23)

Swaps the contents with those of other.

  1. The contained values are swapped as follows:
Value of has_value() Value of other.has_value()
true false
true using std::swap;swap(val, rhs.val); see below
false other.swap(*this); using std::swap;swap(unex, rhs.unex);

[edit] Parameters

other - the expected object to exchange the contents with

[edit] Exceptions

[edit] Example

#include #include #include   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{CAT FACE}"); Ex ex2{"\N{GREEN HEART}"}; show(ex1, ex2, "after ex1.swap(ex2):\n"); ex1.swap(ex2); show(ex1, ex2, "\n\n");   ex2 = std::unexpected(13); show(ex1, ex2, "after ex1.swap(ex2):\n"); ex1.swap(ex2); show(ex1, ex2, "\n\n");   ex2 = std::unexpected(37); show(ex1, ex2, "after ex1.swap(ex2):\n"); ex1.swap(ex2); show(ex1, ex2); }

Output:

ex1.value() = 🐱 ex2.value() = 💚 after ex1.swap(ex2): ex1.value() = 💚 ex2.value() = 🐱   ex1.value() = 💚 ex2.error() = 13 after ex1.swap(ex2): ex1.error() = 13 ex2.value() = 💚   ex1.error() = 13 ex2.error() = 37 after ex1.swap(ex2): ex1.error() = 37 ex2.error() = 13

[edit] See also