From 2903106618275152142
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,515fa24b8aaed57
X-Google-Attributes: gidf78e5,public
From: clamage@Eng.Sun.COM (Steve Clamage)
Subject: Re: Example in "The C++ Workbook" by Wiener and Pinson
Date: 1995/07/31
Message-ID: <3vjkij$ctk@engnews2.Eng.Sun.COM>#1/1
X-Deja-AN: 107303142
references: <3ujj8d$o4m@scapa.cs.ualberta.ca> <9520904.20199@mulga.cs.mu.OZ.AU> <3vj9ak$49m@news.rrz.uni-koeln.de>
organization: Sun Microsystems Inc., Mountain View, CA
newsgroups: comp.std.c++

a2675528@athena.rrz.Uni-Koeln.DE (Paul Sponagl) writes:

>>	template < class T >
>>	void swap(T & item1, T & item2)
>>	{
>>		T temp = item1;
>>		item1 = item2;
>>		item2 = temp;
>>	}

>or do like that

>	inline template < class T > void swap(T& a, T& b) 
>	{
>		a ^=b; b^=a;a ^=b;
>	}

I had hoped that this old idea was dead, but I guess it isn't.

First of all, the code will compile only if operator^= is available.
For built-in types, this is true only for the integer types. You
can't swap floats, doubles, or pointers, for example.

Secondly, it doesn't always give the correct answer. Here is
a simple test case:

	int i = 2;
	cout << i << endl; // prints '2'
	swap(i, i); 
	cout << i << endl; // prints '0'

The original template works for all types which have assignment
defined. Every type can be assigned unless you take steps to
prevent it.
--
Steve Clamage, stephen.clamage@eng.sun.com



