7
#include <tuple>

struct X {
    int i = 0;
    friend constexpr bool operator<(const X &l, const X &r) noexcept {
        return l.i < r.i;
    }
};

struct Y {
    int i = 0;
    constexpr operator bool() const noexcept {
        return i != 0;
    }
    friend constexpr bool operator<(const Y &l, const Y &r) noexcept {
        return l.i < r.i;
    }
};

int main() {
    constexpr X a{1}, b{2};
    static_assert(std::tie(a) < std::tie(b));

    constexpr Y c{1}, d{2};
    static_assert(c < d);
    // assert failed
    // static_assert(std::tie(c) < std::tie(d));

    return 0;
}

I'm compiling with C++20.

Line static_assert(std::tie(c) < std::tie(d)); will fail. It turns out that when comparing c and d, operator bool is called instead of operator<. Why would operator bool get involved in the first place?

I find this quite surprising. Is this intended or a bug?

4
  • 5
    Make the bool conversion operator explicit? Feb 2 at 14:29
  • @Someprogrammerdude Thanks! this will solve the issue. I should not have left it non-explicit. But still, why would it prefers bool conversion?
    – felix
    Feb 2 at 14:31
  • 7
    It looks like something about C++20 and the spaceship operator is to blame. The code works fine in C++17 mode but fails in C++20. Feb 2 at 14:32
  • 1
    It's worth pointing out that the code was always questionable: note that static_assert(c < d) but also static_assert(!(d > c))
    – Barry
    Feb 2 at 16:22

1 Answer 1

9

When comparing two tuple<T>s, named t1 and t2, the operator<=> overload for tuple will use get<0>(t1) <=> get<0>(t2) to compare elements when type T satisfies three_­way_­comparable; otherwise, it will use operator<.

Since Y is implicitly convertible to bool, this makes y <=> y a valid expression and satisfies three_­way_­comparable, such that std::tie(c) < std::tie(d) (unexpectedly) invokes bool(c) <=> bool(d) in your example.

3
  • Your answer is great.. But the fact it works like this makes me really sad :(
    – divinas
    Feb 2 at 17:04
  • Implement operator <=> instead of operator < for your types.
    – Jarod42
    Feb 2 at 17:38
  • 1
    @Jarod42: But then you lose compatibility with a whole lot of compilers which implement older (but still recent) standards of C++.
    – Ben Voigt
    Feb 2 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.