最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - std::three_way_comparable returns false for a non-default `operator<=>` - Stack Overflow

programmeradmin0浏览0评论

I'm attempting to define operator<=> on a class, however when I specify a non-defaulted implementation, std::three_way_comparable returns false:

#include <cstdio>
#include <compare>

using namespace std;

struct UDTC
{
    int i_;
    UDTC(int i) : i_(i) {}

#if 1
    friend std::strong_ordering operator<=>(const UDTC &lhs, const UDTC &rhs) {
        return lhs.i_ <=> rhs.i_;
    }
#else
    friend std::strong_ordering operator<=>(const UDTC &lhs, const UDTC &rhs) = default;
#endif
};


int main(void)
{
    if constexpr (std::three_way_comparable<UDTC>) {
        fprintf(stderr, "UDTC is three_way_comparable\n");
    } else {
        fprintf(stderr, "UDTC is NOT three_way_comparable\n");
    }
}

When I execute this with Visual Studio 2022 or GCC 12, if the <=> function is defaulted, three_way_comparable returns true. If I provide my own implementation, it returns false. I can only assume that my implementation is somehow incomplete, but I'm not seeing what I'm missing.

I'm attempting to define operator<=> on a class, however when I specify a non-defaulted implementation, std::three_way_comparable returns false:

#include <cstdio>
#include <compare>

using namespace std;

struct UDTC
{
    int i_;
    UDTC(int i) : i_(i) {}

#if 1
    friend std::strong_ordering operator<=>(const UDTC &lhs, const UDTC &rhs) {
        return lhs.i_ <=> rhs.i_;
    }
#else
    friend std::strong_ordering operator<=>(const UDTC &lhs, const UDTC &rhs) = default;
#endif
};


int main(void)
{
    if constexpr (std::three_way_comparable<UDTC>) {
        fprintf(stderr, "UDTC is three_way_comparable\n");
    } else {
        fprintf(stderr, "UDTC is NOT three_way_comparable\n");
    }
}

When I execute this with Visual Studio 2022 or GCC 12, if the <=> function is defaulted, three_way_comparable returns true. If I provide my own implementation, it returns false. I can only assume that my implementation is somehow incomplete, but I'm not seeing what I'm missing.

Share Improve this question asked Feb 6 at 1:03 DRHDRH 8,3582 gold badges36 silver badges45 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 31

According to cppreference, concept std::three_way_comparable<T> includes (exposition only) concept __WeaklyEqualityComparableWith<T, T>. In other words, to satisfy this concept, struct UDTC also needs operator==. When you use operator<=>(/*...*/) = default, the compiler also generates operator== for you. If you define your own operator<=>, you must also define operator==. If you add

  friend bool operator==(const UDTC &lhs, const UDTC &rhs) {
        return lhs.i_ == rhs.i_;
    }

to the program, it prints "UDTC is three_way_comparable" as expected.

发布评论

评论列表(0)

  1. 暂无评论