C ++ function template with flexible return type

Say we have such a function

template <class T, class T2>
T getMin(T a, T2 b) {
  if(a < b)
    return a;
  return b;
}

if we call such a function

int a, b;
long c;

a = getMin(b, c);

if c is <a, then the value of c will be of type cast from int.

Is it possible to make the type of the return type flexible so that it returns int or long or any other type that is considered smaller by "<" without casting the type?

change: the type involved in the function can be anything from a simple type to complex classes, where type conversion will not be possible at one time.

+5
source share
2 answers

C ++ 0x allows you to use a keyword autoto give the compiler time to return an expression.


++ 03 , , Promotion, , , .

template<> class Promotion< long, int > { typedef long strongest; }
template<> class Promotion< int, long > { typedef long strongest; }

:

template< typename T1, typename T2 >
Promotion<T1,T2>::strongest function( const T1 &a, const T2 &b ) { ... }

, Promotion .


: , ( ) :

. , , .

, , .

+9

, , . , int double double; char* string string. promote<> .

template <class T1, class T2>
typename promote<T1, T2>::type getMin(T1 const& a, T2 const& b) {
  if(a < b)
    return a;
  return b;
}

, T1 T2 - (, string),

template <class T>
T &getMin(T &a, T &b) {
  if(a < b)
    return a;
  return b;
}

. , , , T const&, . getMin(a + b, b + c), , . .

+1

All Articles