How to write a generic swap function in C++

1 Answer

0 votes
#include <iostream>
#include <string>

/*
 * generic_swap
 * ------------
 * A fully generic C++ swap function implemented using templates.
 *
 * Parameters:
 *   a, b  - references to the two objects to swap
 *
 * This function uses std::swap internally, which is the idiomatic
 * and type‑safe way to swap objects in C++. It works for:
 *   - built‑in types (int, double, etc.)
 *   - std::string
 *   - structs/classes
 *   - containers
 *   - user‑defined types with a valid swap operation
 */
template <typename T>
void generic_swap(T& a, T& b) {
    std::swap(a, b);
}

/*
 * Print arrays of integers
 */
void print_int_array(const int* arr, int n) {
    for (int i = 0; i < n; i++)
        std::cout << arr[i] << " ";
    std::cout << "\n";
}

int main() {
    std::cout << "=== TEST 1: Swap integers ===\n";
    int x = 10, y = 20;
    std::cout << "Before: x=" << x << ", y=" << y << "\n";
    generic_swap(x, y);
    std::cout << "After:  x=" << x << ", y=" << y << "\n\n";

    std::cout << "=== TEST 2: Swap doubles ===\n";
    double a = 3.14, b = 2.71;
    std::cout << "Before: a=" << a << ", b=" << b << "\n";
    generic_swap(a, b);
    std::cout << "After:  a=" << a << ", b=" << b << "\n\n";

    std::cout << "=== TEST 3: Swap structs ===\n";
    struct Point { int x, y; };
    Point p1{1, 2}, p2{9, 8};
    std::cout << "Before: p1=(" << p1.x << "," << p1.y
              << "), p2=(" << p2.x << "," << p2.y << ")\n";
    generic_swap(p1, p2);
    std::cout << "After:  p1=(" << p1.x << "," << p1.y
              << "), p2=(" << p2.x << "," << p2.y << ")\n\n";

    std::cout << "=== TEST 4: Swap array elements ===\n";
    int arr[] = {1, 2, 3, 4, 5};
    std::cout << "Before: ";
    print_int_array(arr, 5);
    generic_swap(arr[1], arr[3]);
    std::cout << "After:  ";
    print_int_array(arr, 5);
    std::cout << "\n";

    std::cout << "=== TEST 5: Swap strings ===\n";
    std::string str1 = "Hello";
    std::string str2 = "World";
    std::cout << "Before: str1=\"" << str1 << "\", str2=\"" << str2 << "\"\n";
    generic_swap(str1, str2);
    std::cout << "After:  str1=\"" << str1 << "\", str2=\"" << str2 << "\"\n\n";
}



/*
run:

=== TEST 1: Swap integers ===
Before: x=10, y=20
After:  x=20, y=10

=== TEST 2: Swap doubles ===
Before: a=3.14, b=2.71
After:  a=2.71, b=3.14

=== TEST 3: Swap structs ===
Before: p1=(1,2), p2=(9,8)
After:  p1=(9,8), p2=(1,2)

=== TEST 4: Swap array elements ===
Before: 1 2 3 4 5 
After:  1 4 3 2 5 

=== TEST 5: Swap strings ===
Before: str1="Hello", str2="World"
After:  str1="World", str2="Hello"

*/

 



answered 9 hours ago by avibootz
...