[cfe-dev] [libc++] Should std::max allow types that require explicit bool conversion?

Jö Fahlke via cfe-dev cfe-dev at lists.llvm.org
Thu Jul 5 11:23:23 PDT 2018


I was surprised to find that I cannot use libc++'s `std::max(a, b)` if `a<b`
yields an object with an explicit operator bool.  Is that intended, or should
I file a bug?

It seems to work for libstdc++.  It also works if I use `std::max(a, b, cmp)`
and the result of `cmp(a, b)` has an explicit operator bool.

Full example <https://godbolt.org/g/cTqgvz>:
#include <algorithm>

struct bwrap {
    bool value;
    explicit operator bool() const { return value; }

struct iwrap {
    int value;

bwrap operator<(iwrap a, iwrap b) { return {a.value < b.value}; }
bwrap cmp(iwrap a, iwrap b) { return {a.value < b.value}; }

int main()
  auto v = std::max(iwrap{0}, iwrap{1});
  //auto v = std::max(iwrap{0}, iwrap{1}, cmp);
  return v.value;

I tried to look look in the standard (specifically, C++17), but I can't quite
figure it out:

- The two-argument signature requires LessThanComparable, which requires that
  the return type of `a < b` be "convertible to bool" -- it doesn't say
  whether implicitly or contextually (or at least I can't find where it does).

- For the three-argument version there is a clear statement that the return
  type of `cmp(a, b)` is contextually converted to bool in [alg.sorting].

cppreference did not seem very trustworthy on that matter:

- For the two-argument version and LessThanComparable, it requires the
  stricter "implicitly convertible to bool".

- For the three-argument version, it requires that the comparison object
  adheres to the "Compare" requirement.  The documentation for "Compare"
  contradicts itself: it says "contextually convertible" in the introduction,
  but "implicitly convertible" in the requirements table.

The contradition makes me reluctend to blindly trust cppreference on

I'd be thankful if someone has hints on this one,

Note: These sparked the whole thing:

Jorrit (Jö) Fahlke, Institute for Computational und Applied Mathematics,
University of Münster, Orleans-Ring 10, D-48149 Münster
Tel: +49 251 83 35146 Fax: +49 251 83 32729

If God had intended Man to Smoke, He would have set him on Fire.
-- fortune
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20180705/78cbadee/attachment.sig>

More information about the cfe-dev mailing list