13

I vaguely remember I saw somewhere a discussion on this but I cannot find it now; "non-const min max c++" and similar variants give no relevant results.

Why doesn't the C++ standard library include the following non-const overload of std::min (and similarly for std:max)?

template <typename T>
T& min(T& a, T& b);

It could be useful sometimes, e.g. if I want to increase the lower number:

std::min(x, y) += 1;

Are there any problems this overload would cause?

Barry
  • 286,269
  • 29
  • 621
  • 977
Nikola Benes
  • 2,372
  • 1
  • 20
  • 33
  • 3
    https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/tnx2SaxEpYE – Vittorio Romeo Sep 27 '18 at 11:14
  • 3
    If they both have the *same value*, which one gets updated? – Galik Sep 27 '18 at 13:14
  • The first one, as per the standard behaviour of std::min, see https://en.cppreference.com/w/cpp/algorithm/min. “Returns: The smaller of a and b. If the values are equivalent, returns a.” – Nikola Benes Sep 27 '18 at 15:34

1 Answers1

13

This was proposed by Howard E. Hinnant in N2199: "Improved min/max", which according to this discussion was rejected.

In the same discussion Howard mentions these as the reasons for the rejection:

The implementation was considered too complicated at the time. Though I haven’t tried, it could almost surely be done much more simply in today’s language/library. At the very least what is called “promote” in the implementation is today called “std::common_type”.

Part of the complication is that I attempted to solve several problems at the same time:

  1. Being able to assign into the result of min (but only when safe to do so).
  2. Eliminate dangling reference dangers at compile-time.
  3. Support heterogeneous integral comparisons, weeding out dangerous combinations at compile-time.
  4. Support move-only types.

As T.C. mentions in the same discussion, a proposal would also need to not break code such as:

int i = 1; std::min(i, 0);

If you're interested in solving the problems mentioned in the discussion and writing a proposal + example implementation, then this could eventually make it into the Standard.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416