I want to make swap function, which can take two different type of variables as parameters. for example)
int a = 2;
double b = 1.1
swap(a,b)//wish a = 1.1, b = 2
template<typename T, typename U>
void swap(T& x, U& y)//it doesn't work due to automatic type cast
{
U temp = x;
x = y;
y = temp;
std::cout << "swap" << std::endl;
}
You cannot do that because the objects types can't be changed. the double will be truncated as an int and the integer will be saved as a double. However, you can use
std::variant
s, as followsDemo