C++ Function Template With Flexible Return Type

前端 未结 2 1704
说谎
说谎 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 
    typename promote::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 
    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.

提交回复
热议问题