Aim:
To write a C++ program for swapping two values using function templates
Description:
- Function templates are special functions that can operate with generic types.
- This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.
- In C++ this can be achieved using template parameters.
- A template parameter is a special kind of parameter that can be used to pass a type as an argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
- These function templates can use these parameters as if they were any other regular type.
- The format for declaring function templates with type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
Code language: HTML, XML (xml)
- The only difference between both prototypes is the use of either the keyword class or the keyword typename.
- Its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.
- For example, to create a template function that returns the greater one of two objects we could use:
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
Code language: JavaScript (javascript)
- Here we have created a template function with myType as its template parameter.
- This template parameter represents a type that has not yet been specified, but that can be used in the template function as if it were a regular type.
- As you can see, the function template GetMax returns the greater of two parameters of this still-undefined type.
- To use this function template we use the following format for the function call:
function_name <type> (parameters);
Code language: HTML, XML (xml)
Algorithm:
- Start the program
- Create a class with templates.
- Â Create a class for sort functions.
- Â Swap the values for using bubble sort
- Â Display the result.
Program:
#include<iostream> using namespace std; template <class T> void Swap(T &x, T &y) { T temp; temp = x; x = y; y = temp; } int main() { int x, y; cout << "Enter two numbers:"; cin >> x>>y; cout << "Before Swap:"; cout << "\nx value is:" << x; cout << "\ny value is:" << y; Swap(x, y); cout << "\n\nAfter Function Templates:\n"; cout << "\nx value is:" << x; cout << "\ny value is:" << y; return 0; }
Execution:
Input 33 77 Output Enter two numbers: Before Swap: x value is:33 y value is:77 After Function Templates: x value is:77 y value is:33
Result:
Thus, the Swapping Two Values using Function Templates was executed successfully.