<=> 三路比较运算符
缺省比较
对于如下运算符:<、<=、>=、>, 如果<=>没有被定义,则这些运算符的默认实现即是将它们声明为deleted;否则,这些运算符将通过调用并判断<=>的返回值以确定两个 *** 作数的大小关系。
对于!=运算符:如果没有被定义,则!=的默认实现即是将它声明为deleted;否则,!=的默认实现将调用并将其返回值逻辑求反作为!=的返回值。
三路比较运算符
基于该运算符可以生成其他常用运算符,但它没有为我们提供缺省的运算符, 我们可以通过一行公式去定义它们,
struct s{
char a;
int b;
friend std::strong_order operator<=>(s,s) = default;
};
s s1 = {'a', 1};
s s2 = {'a', 1};
bool b0 = s1==s2; //true
int b1 = s1<=>s2; //0
bool b2 = s1<s2; //false
此方案是在2017年提议, 但是在2020年才被引入;
引入我们知道比较运算符有如下六种:
1. ==
2. !=
3. <
4. <=
5. >
6. >=
但是C/C++ 并没有给数据结构提供缺省的比较。
比如:
struct s{
char a;
int b;
};
s s1 = {'a', 1};
s s2 = {'a', 1};
void test(){
s s3 = s1; //可以初始化
s2 = s1; //可以赋值
if(s1 == s2){ //error ==对s 没定义
/*do something*/
}
也就是说对于用户没有显示定义这些数据结构operator==() 或者 operator<(), 它们就没法支持简单的数据结构。
为啥没有提供默认缺省比较呢, 主要是考虑到s的通常内存结构, 在持有s内存中部分会有“未使用的比特位”。
因为如此,s1==s2结果可能会由于这些“未使用的比特位”导致会给出false.
如果我们要显示定义的话, 那么有一个繁琐问题就是要处理写六行代码
class A{
......
bool operator==(const A&) const = default;
bool operator!=(const A&) const = default;
bool operator<(const A&) const = default;
bool operator<=(const A&) const = default;
bool operator>=(const A&) const = default;
bool operator>(const A&) const = default;
......
};
综上所需, 最后提案所需三路比较运算符(可以将<、<=、>=、>)可以省很多繁琐事,
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)