Write a generic function that swaps values in two variables. Your function should have two parameters of the same type. Test the function with int, double and string values.
Was wondering if someone could give me some hints on where to even start. I don't really even know what the question is asking for. Thanks
i'm not sure what it means by test the function with int, double, and string values.
Note: I'm referring to Chrisname's code snippet.
It's relatively simple. You call the template method with the specified types such as: swap < Type-Specifier > ( ..., ... );Note: Where 'Type-Specifier' is either one your your target types.
#include <iostream>
usingnamespace std;
template <typename T>
void swap(T &n1, T &n2) // Note the &
{
T temp=n1; // Note use the type T
n1=n2;
n2=temp;
}
int main()
{
int a = 2;
int b = 3;
swap(a, b); // Now a = 3 and b = 2
double x = 2.3;
double y = 4.5;
swap(x, y); // Now x = 4.5 and y = 2.3
}