NoSenseEtAl
NoSenseEtAl

Reputation: 30048

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

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:

Upvotes: 4

Views: 206

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473577

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.

Upvotes: 5

Related Questions