Title
Inconsistency between `value_or()` and `error_or()` in `std::expected`
Status
new
Section
[optional.observe] [expected.object.obs]
Submitter
Hiroaki Ando

Created on 2025-06-27.00:00:00 last changed 6 days ago

Messages

Date: 2025-07-01.09:30:27

In [expected.object.obs]/19, the return value of `value_or()` is specified as follows:

Returns: has_value() ? **this : static_cast<T>(std::forward<U>(v)).
Meanwhile, the return value of `error_or()` is specified as follows ([expected.object.obs]/23):
Returns: std::forward<G>(e) if has_value() is true, error() otherwise.
Since these functions appear to be dual in nature, it would be preferable to maintain consistent notation.

Jonathan adds: The wording in `expected::error_or` is newer, having been added by P2505R5, and intentionally avoided a conditional expression (the problems with conditional expressions explained in p3177r0 don't actually affect these member functions, due to the non-const prvalue return type, but determining that there are no pessimized copies in `value_or` wouldn't be necessary if we didn't specify it with a conditional expression). The `error_or` wording also avoids using an explicit conversion when the Mandates: element requires implicit conversion to work anyway. We might want to rephrase the `value_or` wording to match `error_or`, or possibly make `value_or` and `error_or` even more explicit, specifying them in terms of `if`-`else`: :

Effects: Equivalent to:

if (has_value())
  return **this;
else
  return std::forward<U>(v);
History
Date User Action Args
2025-06-27 00:00:00admincreate