
template swap
Can someone please take a look at this futile attempt of mine at writting a function template for a function swap its 2 parameters. Also, in order for swap to do its designated task, do I have to pass the two objects by reference? Do both the templates do the same thing? Or did I go overboard on the first one?
Thank you,
Laina
template 1
template <class DataType>
void swap(DataType & a, DataType & b)
{
DataType temp = a;
a = b;
b = temp;
}
void swap(float & a, float & b)
{
int temp = a;
a = floor(b + .5); //rounds to the nearest integer
b = floor(temp + .5); //rounds to the nearest integer
}
template <class DataType>
void swap(DataType & a, DataType & b, DataType & c)
{
DataType temp = a;
a = b;
b = c;
c = temp;
}
template 2
template <typename t>
void swap(t& A, t& B) {
t T(A);
A = B;
B = T;
}

overload
Do I have to overload a function or operator by an object in order to use this function?

Those templates should work for any class that has a copy constructor and an assignment operator defined.

void swap(float & a, float & b)
{
int temp = a;
a = floor(b + .5); //rounds to the nearest integer
b = floor(temp + .5); //rounds to the nearest integer
}
small mistake..... temp should be a float.