Scroll to navigation

std::swap(std::tuple)(3) C++ Standard Libary std::swap(std::tuple)(3)

NAME

std::swap(std::tuple) - std::swap(std::tuple)

Synopsis

Defined in header <tuple> template< class... Types >
(since C++11) void swap( std::tuple<Types...>& lhs, (until C++20)

std::tuple<Types...>& rhs ) noexcept(/* see below */); template< class... Types >

constexpr void swap( std::tuple<Types...>& lhs, (1) (since C++20)

std::tuple<Types...>& rhs ) noexcept(/* see below */); template< class... Types >

constexpr void swap( const std::tuple<Types...>& lhs, (2) (since C++23)

const std::tuple<Types...>& rhs ) noexcept(/* see below */);

Swaps the contents of lhs and rhs. Equivalent to lhs.swap(rhs).

1) This overload participates in overload resolution only if std::is_swappable_v<Ti> is true for all i from 0 to sizeof...(Types). (since C++17) 2) This overload participates in overload resolution only if std::is_swappable_v<const Ti> is true for all i from 0 to sizeof...(Types).

Parameters

lhs, rhs - tuples whose contents to swap

Return value

(none)

Exceptions

noexcept specification: noexcept(noexcept(lhs.swap(rhs)))

Example

// Run this code

#include <iostream> #include <string> #include <tuple>

int main() {
std::tuple<int, std::string, float> p1{42, "ABCD", 2.71}, p2;
p2 = std::make_tuple(10, "1234", 3.14);


auto print_p1_p2 = [&](auto rem)
{
std::cout << rem
<< "p1 = {" << std::get<0>(p1)
<< ", " << std::get<1>(p1)
<< ", " << std::get<2>(p1) << "}, "
<< "p2 = {" << std::get<0>(p2)
<< ", " << std::get<1>(p2)
<< ", " << std::get<2>(p2) << "}\n";
};


print_p1_p2("Before p1.swap(p2): ");
p1.swap(p2);
print_p1_p2("After p1.swap(p2): ");
swap(p1, p2);
print_p1_p2("After swap(p1, p2): "); }

Output:

Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14} After p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71} After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}

See also

swap swaps the contents of two tuples
(public member function) std::swap(std::pair) specializes the std::swap algorithm (C++11) (function template)

2026.11.10 http://cppreference.com