C++ 在C+;中有没有更好的方法来定义关系运算符+;C&x2B之前+;20?

C++ 在C+;中有没有更好的方法来定义关系运算符+;C&x2B之前+;20?,c++,operators,c++17,comparison-operators,C++,Operators,C++17,Comparison Operators,对我来说,编写这样的代码是相当乏味的 class date { private: int day, year, month; int comp(const date & Other) const; public: date(int D, int Y, int M) : day (D), year (Y), month (M) {} friend bool operator==(const date & L, const date &

对我来说,编写这样的代码是相当乏味的

class date {
private: 
    int day, year, month;
    int comp(const date & Other) const;
public:
    date(int D, int Y, int M) : day (D), year (Y), month (M)  {}

    friend bool operator==(const date & L, const date & R) { return L.comp(R) == 0 ; }
    friend bool operator!=(const date & L, const date & R) { return L.comp(R) != 0 ; }
    friend bool operator> (const date & L, const date & R) { return L.comp(R) > 0 ; }
    friend bool operator>=(const date & L, const date & R) { return L.comp(R) >= 0 ; }
    friend bool operator< (const date & L, const date & R) { return L.comp(R) < 0 ; }
    friend bool operator<=(const date & L, const date & R) { return L.comp(R) <= 0 ; }
}
上课日期{
私人:
整数天、年、月;
国际公司(施工日期和其他)施工;
公众:
日期(int D,int Y,int M):日(D),年(Y),月(M){
friend bool运算符==(const date&L,const date&R){return L.comp(R)==0;}
友元布尔运算符!=(const date&L,const date&R){返回L.comp(R)!=0;}
friend bool操作符>(const date&L,const date&R){return L.comp(R)>0;}
友元布尔运算符>=(常数日期&L,常数日期&R){return L.comp(R)>=0;}
友元布尔运算符<(const date&L,const date&R){返回L.comp(R)<0;}
friend bool操作符您可以使用(或自己实现这样的东西),但您仍然需要编写两个函数:

class date : public totally_ordered<date> {
private: 
    int day, year, month;
    int comp(const date & Other) ;
public:
    date(int D, int Y, int M) : day (D), year (Y), month (M)  {}

    friend bool operator==(const date & L, const date & R) { return L.comp(R) == 0 ; }
    friend bool operator< (const date & L, const date & R) { return L.comp(R) < 0 ; }
}

如果您愿意牺牲一点性能(例如,进行两倍的比较),CRTP(奇怪的重复模板模式)可能在这里工作。Boost将帮助模板化操作符?因此您只需要实现比较?可能会发出非常糟糕的错误消息“肯定有更好的方法来完成所有这些。”胡说八道。如果有更好的方法,C++20就不必创建更好的方法。偏序到底是什么?@JohnJenkins最简单的答案是:不满足三分法的顺序——给定一对元素,它们之间可能没有顺序。例如,集合的子集。
{1}<{1,2}
{1,2}>{2}
但是如果你将
{1}
{2}
进行比较,它既不是
也不是
也不是
=
class date {
private: 
    int year, month, day; // NB: I reordered these
public:
    friend auto operator<=>(const date&, const date&) = default;
};