yungman
				
				
			 
			
	
	
	
		
	
	
			
		
		
			
			
				- 5,741
 
- 294
 
Hi
I want to see whether there is a way to make this program work without much complication. I read from Ivor book that you can work with two different type of variables for example mixing int x = 1 and double y = 2.5 and use template to swap them using declaration <double> in the program as shown in the line 13. But I run into problem, this method will not work if I use reference for arguments as show in line 4. It will give me an error.
Obviously, it I remove the '&' to pass by value, it would not give an error, BUT it won't work as it's shallow copy. The values pass into the swapVars() and actually does the swapping when I step through it. But I cannot copy back into x and y as var1 and var2 are destroy once they go out of scope. Is there any way easy to make this work with reference as argument?
	
	
	
    
	
		
The error message is:
		
		
	
	
		
	
Below is the program passing by value, I stepped through and you can see the local window shows the two numbers are successfully swapped. But like I said, this is shallow copy, I cannot pass the value back to x and y. This might be useful when dealing with mix type numbers if I can make it work.
		
	
thanks
				
			I want to see whether there is a way to make this program work without much complication. I read from Ivor book that you can work with two different type of variables for example mixing int x = 1 and double y = 2.5 and use template to swap them using declaration <double> in the program as shown in the line 13. But I run into problem, this method will not work if I use reference for arguments as show in line 4. It will give me an error.
Obviously, it I remove the '&' to pass by value, it would not give an error, BUT it won't work as it's shallow copy. The values pass into the swapVars() and actually does the swapping when I step through it. But I cannot copy back into x and y as var1 and var2 are destroy once they go out of scope. Is there any way easy to make this work with reference as argument?
		C++:
	
	#include <iostream>
using namespace std;
template <class T>
void swapVars(T &var1, T &var2)
{    T temp;
    temp = var1;
    var1 = var2;
    var2 = temp;
}
int main()
{    int  x = 1;   
    double y = 2.5;
    swapVars<double>(x, y);
    cout << " Swap int x=1 with double y=2.5 = " << x << ", " << y << "\n\n";
    return 0;
}
	Below is the program passing by value, I stepped through and you can see the local window shows the two numbers are successfully swapped. But like I said, this is shallow copy, I cannot pass the value back to x and y. This might be useful when dealing with mix type numbers if I can make it work.
thanks