Is the below function definition is legal or not?
T& GetMax(const T& t1, const T& t2)
{
if (t1 > t2)
{
return t2;
}
// else
return t2;
}
It is written that :
“At the return statements, compiler would complain that t1 or t2 cannot be converted to non-const.”
I read it in this site : http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1
Does it mean that it is illegal ,if not what else? Could you provide example of use of it?
Could you provide some clear explanation to me ?
Thanks in advance
Why should it be illegal? Your function can use some global state to return, while it is forbidden to return its arguments.
ADDED
You cannot return one of your argument, because it will violate
constconstrains. You canif returning non-const in your case would be possible, one could write
which has no sense.
You can not also return reference to some temporary automatic variable, created inside function, as it will be destroyed, when function finished.