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.
You cannot swap in-place, since
T1andT2need not be of the same type.Pair<T1,T2>is a different type thanPair<T2,T1>. You have to return an object of a different type than the original one, so that has to be a new object.What I’d do is this:
(There’s no reason to make this a member of your
Pairtemplate.)You could, however, add an overload for when
T1andT2are of the same type:But this, as Dennis mentioned in his comment, might be indeed very confusing.
Another idea is to define a converting constructor for your
Pairtemplate, so that implicitly convertible types can be swapped:Then you can swap like this:
But note that this also supports other, probably unwanted implicit conversions: