C++ Template: return larger value of two different types and preserve original type

Viewed 174

I'm confused about this template example on: https://www.cplusplus.com/doc/oldtutorial/templates/ If I called function with the values GetMin(1, 0.1);I get a result of 0. Assuming it's incorrect, how would you do it correctly while still returning the result as its original type (Meaning you can't set the return type of double and convert the result to a double).

template <class T, class U>
T GetMin (T a, U b) {
  return (a<b?a:b);
}
2 Answers

You can use std::common_type (docs) for getting common of 2 (or more) types (common type for T and U is the type that T and U can implicitly be converted to):

 template <class T, class U>
 typename common_type<T, U>::type GetMin (T a, U b) {
      return (a<b?a:b);
 }

Since C++14 the helper common_type_t<T, U> can also be used, to save some writing.

how would you do it correctly while still returning the result as its original type

You can't do that, because the return value is decided at run-time, but the return type is decided at compile time. Assuming a common type that both of the arguments can be converted to is OK, here is one way implement that function:

template <typename T, typename Y>
auto GetMin(T const& a, Y const& b) {
  return (a < b ? a : b);
}

Result of the conditional operator is a common type that both operands can be converted to, so the return type is going to be double when you do GetMin(1, 0.1);. This is, most of the time, what you want anyway.


You could also do something like this. But, why would you do that?

Related