Article View: comp.std.c++
Article #1514Re: Example in "The C++ Workbook" by Wiener and Pinson
From: Steve Clamage
Date: Mon, 31 Jul 1995 22:13
Date: Mon, 31 Jul 1995 22:13
36 lines
1439 bytes
1439 bytes
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
Technical Details
Message-ID:
<3vjkij$ctk@engnews2.Eng.Sun.COM>Path:
arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!clamageReferences:
<3ujj8d$o4m@scapa.cs.ualberta.ca> <9520904.20199@mulga.cs.mu.OZ.AU> <3vj9ak$49m@news.rrz.uni-koeln.de>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!clamage From: clamage@Eng.Sun.COM (Steve Clamage) Newsgroups: comp.std.c++ Subject: Re: Example in "The C++ Workbook" by Wiener and Pinson Date: 31 Jul 1995 22:13:39 GMT Organization: Sun Microsystems Inc., Mountain View, CA Message-ID: <3vjkij$ctk@engnews2.Eng.Sun.COM> References: <3ujj8d$o4m@scapa.cs.ualberta.ca> <9520904.20199@mulga.cs.mu.OZ.AU> <3vj9ak$49m@news.rrz.uni-koeln.de> NNTP-Posting-Host: taumet.eng.sun.com X-Newsreader: NN version 6.5.0 #21 (NOV)