Let’s say that we have a function like so
template <class T, class T2>
T getMin(T a, T2 b) {
if(a < b)
return a;
return b;
}
if we call the function like so
int a, b;
long c;
a = getMin(b, c);
if c is < a, then the value of c will be type casted to int.
Is it possible to make the return type flexible so that it would return an int, or long, or any other type considered smaller by “<” without being type casted?
edit :
the type involved in the function can be anything from simple type to complex classes where typecasting sometime won’t be possible.
C++0x will allow you to use the
autokeyword in order to let the compiler derive the return time of an expression.For C++03 the only way I found to automatize such process is to define a template class
Promotionthat defines the strongest type between two types, and then specialize it for any couple of types you might need to use.and thus:
If you choose to try this solution, I’d suggest to generate the Promotion specializations with an automatically generated header file.
Edit: I reread the question after reading the other (now deleted) answer:
You can’t return the type of the smaller variable. That’s because the value of the variables will only be found out at runtime, while your function return type must be defined at compile time.
The solution I proposed will return always the strongest type between the two variables’ type.