Could C++ concepts be used to implement mixed type min and max in C++?

Viewed 134

As you may know std::max and std::min "suffer" from the fact they have 1 template argument, so even simple max(container.size(), 47) will not work since .size() returns size_t and 47 is int.

I know there was historically proposal to add proper overloads to C++ but it was rejected. But from what I know it was mostly due to paper being too complex for not enough gain, so I wonder if one would use std::common_range_t as return value (invented type trait that gives you int/float big enough to hold the min/max of mixed arguments, else hard error) would that be fine...

So to finally get to my question: If we want min/max extended to take 2 template arguments as described above are there any backward compatibility or any other issues that prevent that?

note:

  • This is mostly is it technically possible question, I am not interested if WG21 plans to do anything to standardize this, mostly curious about potential technical limitations.
  • C++17 version of this question(for some reason heavily downvoted ), but more general, also deals with some other limitations.
1 Answers

The two-argument std::min/max return references to the parameter that is the min/max. That requires that they be of the same type, since you can't have a function return different types. Nor can you return a reference to a temporary.

The only way to do this is to create a new function that returns a value (probably of type std::common_type), a copy of the min/max. But since it returns a copy rather than a reference, it would not be backwards compatible with std::min/max.

Related