I have to write a template that would swap two arguments, if second one is smaller than first. But in case of string beeing passed to function it would swap them, if second is smaller than first by length. Is it possible to implement that using just one template?
Here is what I have written so far.

template <typename T>
void SWAP(T &A, T &B)
{
	T temp;
	if ( B < A )
	{
		temp = A;
		A = B;
		B = temp;
	}
}

Nah. You'll probably have to specialise the template, I'd say. Or overload a > operator, if you feel like it.

So here is what I've done. Is it made in proper way?

template <typename T>
void SWAP(T &A, T &B)
{
	T temp;
	if ( B < A )
	{
		temp = A;
		A = B;
		B = temp;
	}
}

template <>
void SWAP<string>(string &A, string &B)
//void SWAP(string &A, string &B)
{
	string temp;
	if ( B.length() < A.length() )
	{
		temp = A;
		A = B;
		B = temp;
	}
}

Can somebody post how an overloaded operator < would look like in this case. I am new to this part of C++, but I want to learn it, because it looks like a powerful feature and therefore good thing to know how to use it ! Thanks for any replay, directions, sample.

Thanks for the replay:) Excellent tutorial!
So now I did this:

bool operator <(string &a, string &b){
	return (a.length() < b.length());
}
template <typename T>
void SWAP(T &A, T &B)
{
	T temp;
	if ( B < A )
	{
		temp = A;
		A = B;
		B = temp;
	}
}

Great thing :)

This question has already been answered. Start a new discussion instead.