template< class T1, class T2 >
class Pair {
T1 first;
T2 second;
};
I'm being asked to write a swap() method so that the first element becomes the second and the second the first. I have:
Pair<T2,T1> swap() {
return Pair<T2,T1>(second, first);
}
But this returns a new object rather than swapping, where I think it needs to be a void method that changes its own data members. Is this possible to do since T1 and T2 are potentially different class types? In other words I can't simply set temp=first, first=second, second=temp because it would try to convert them to different types. I'm not sure why you would potentially want to have a template object that changes order of its types as it seems that would cause confusion but that appears to be what I'm being asked to do.
Edit: Thank you all for answering! Pretty much as I thought, swapping in place obviously does not make any sense, the request for the swap() function was quite ambiguous.