swap using Function template in c++

Function templates in C++ allow us to define a generic function that can work with different data types. The "swap" function is commonly implemented using a function template in C++. Here's how you can implement a swap function template in C++:

Step 1: Declare the function template To create a swap function template, we start by declaring the template using the "template" keyword, followed by the template parameter(s) in angle brackets. In this case, we need a single template parameter to represent the data type of the variables we want to swap. We'll use the convention of using the typename keyword followed by a placeholder name (usually "T") to represent the template parameter.

template<typename T>

Step 2: Define the function Next, we define the function template. In this case, we want to swap the values of two variables, so we'll define a function called "swap" that takes references to two variables of type T. Using references allows us to modify the original variables.

void swap(T& a, T& b)

Step 3: Implement the function Inside the function definition, we can simply use a temporary variable to perform the swap. We assign the value of the first variable (a) to the temporary variable, then assign the value of the second variable (b) to the first variable (a), and finally assign the value of the temporary variable to the second variable (b).

{
    T temp = a;
    a = b;
    b = temp;
}

Step 4: Using the function template To use the swap function template, we can simply call it, passing the variables we want to swap as arguments. The compiler will automatically deduce the appropriate data type based on the arguments.

int main()
{
    int x = 5;
    int y = 10;
    swap(x, y); // Swaps the values of x and y
    return 0;
}

In this example, we're swapping two variables of type "int". However, the swap function template can work with any data type for which the assignment operator and copy constructor are defined. This includes built-in types like int, float, and char, as well as user-defined types like class objects.