Here is an example of a C++ template function called "swaps" that interchanges the values of the two arguments sent to it:
csstemplate<typename T>
void swaps(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
Note that the function uses pass-by-reference, as specified in the prompt, to modify the original arguments rather than creating new copies.
Here is a main function to test the "swaps" function with several types:
#include <iostream>
int main() {
int x = 10, y = 20;
std::cout << "Before swapping (int): x = " << x << ", y = " << y << std::endl;
swaps(x, y);
std::cout << "After swapping (int): x = " << x << ", y = " << y << std::endl;
float a = 10.5, b = 20.5;
std::cout << "Before swapping (float): a = " << a << ", b = " << b << std::endl;
swaps(a, b);
std::cout << "After swapping (float): a = " << a << ", b = " << b << std::endl;
char c = 'A', d = 'B';
std::cout << "Before swapping (char): c = " << c << ", d = " << d << std::endl;
swaps(c, d);
std::cout << "After swapping (char): c = " << c << ", d = " << d << std::endl;
return 0;
}
This main function demonstrates how the "swaps" template function can be used with different data types, including int, float, and char. The output of this program would show that the values of the arguments have been successfully interchanged in each case.
No comments:
Post a Comment