C++ Template Swap Function Guide

In C++, to achieve generic mutual assignment, you can use templates and references. The specific method is as follows:

#include <iostream>

template <typename T>
void swap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int a = 5, b = 10;
    std::cout << "a: " << a << ", b: " << b << std::endl;

    swap(a, b);

    std::cout << "After swap:" << std::endl;
    std::cout << "a: " << a << ", b: " << b << std::endl;

    return 0;
}

In the above code, we have defined a template function swap to implement a generic exchange operation. In the main function, we pass in two variables of type int, a and b, and then call the swap function to swap their values. Since the swap function is a template function, it can accept parameters of any type, making it applicable for exchanging values of other variable types as well.

By doing so, we can achieve the operation of assigning generics to each other.

bannerAds