C++ Function Template With Flexible Return Type

前端 未结 2 1696
说谎
说谎 2021-01-03 00:20

Let\'s say that we have a function like so

template 
T getMin(T a, T2 b) {
  if(a < b)
    return a;
  return b;
}
相关标签:
2条回答
  • 2021-01-03 00:52

    As has been said, you want to take the type that is more generic. Like, int and double should become double; char* and string should become string. This works with my promote<> template. Just write

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

    This will always return a copy, even if T1 and T2 is the same type (like string), which is why I would overload it for non-const same-type arguments

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

    These two variants seem to be a reasonable configuration. If you want to have a slightly more risky, but in more cases performant, solution, you can accept T const&, also accepting temporaries. If you then use it like getMin(a + b, b + c), which could pass temporaries, and use the result directly, that's all fine. The result is usable and can still be copied into a local variable.

    0 讨论(0)
  • 2021-01-03 00:57

    C++0x will allow you to use the auto keyword 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 Promotion that defines the strongest type between two types, and then specialize it for any couple of types you might need to use.

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

    and thus:

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

    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.

    0 讨论(0)
提交回复
热议问题