C++20 飞船运算符

270 阅读3分钟

简介

不同于之前的比较运算符只有6中类型:<、>、==、!= <=、>=。C++20提出一种的新的比较运算符——飞船运算符。 飞船运算符也即三路比较运算符(Three-way comparison)。形式如下:

lhs<=>rhs

使用场景

类外

用于进行比较,与<、>、==、!= <=、>=用法相同,只是返回值不同。示例代码如下:

#include <compare>
void using_three_way()
{
	int a =10;
	int b =20;

	std::strong_ordering  res = a<=>b;

	if (res<0)
	{
		std::cout << "a < b \n";
	}
	else if (res ==0)
	{
		std::cout << "a = b \n";
	}
	else
	{
		std::cout << "a > b \n";
	}
}

注意:

  1. 如果lhs和rhs中,只存在一个bool类型,则出现编译错误

	bool a =10.0;
	int b = 5;
	auto   res = a<=>b;//error
  1. 如果操作数存在窄化,则会出现编译错误,
	unsigned int i = 1;
	auto r = -1 < i;    // existing pitfall: returns ‘false’
	auto r2 = -1 <=> i;//error

类内

当自定义类型的数据需要提供比较运算符,可以通过重载<=>运算符,借助编译器生成所有的比较运算符。 在C++20前,应该如是重载比较运算符

struct myValue {
	int value;
	constexpr myValue(int value) : value{ value } { }
	bool operator==(const myValue& rhs) const { return value == rhs.value; }
	bool operator!=(const myValue& rhs) const { return !(*this == rhs); }
	bool operator<(const myValue& rhs)  const { return value < rhs.value; }
	bool operator<=(const myValue& rhs) const { return !(rhs < *this); }
	bool operator>(const myValue& rhs)  const { return rhs < *this; }
	bool operator>=(const myValue& rhs) const { return !(*this < rhs); }
};

如上代码可以实现自定义数据类型myValue的比较,但是如上代码没有书写int和myValue进行比较的友元函数,如下的代码会出现编译错误,

constexpr bool is_gt_42(const myValue& a) {
  return 42 < a;
}

而在C++20后,只需重载三路比较运算符即可,如下:

struct myValue {
	int value;
	constexpr myValue(int value) : value{ value } { }
	std::strong_ordering operator<=>(const myValue& int_wrapper)const =default;
};

仅重载三路比较运算符不仅实现了上述6个关系运算符重载的功能,还具备类外比较的友元函数的功能。 由以上代码可知,<=>更加简洁高效,同时,则如下的代码存在编译错误。

<=>返回值

如果<=>的操作数为整数返回值为std::strong_ordering类型; 如果<=>的操作数存在浮点数返回std::partial_ordering类型; 如果<=>的操作数是相同类型的枚举,操作符则会将操作数转换为枚举数值类型的<=>操作结果,如值类型为int的枚举的作为<=>的操作数,那么操作结果为std::strong_ordering类型; 如果至少有一个操作数是指向对象的指针或指向成员的指针,则对两个操作数应用数组到指针转换、指针转换和限定转换,将它们转换为复合指针类型,并返回std::strong_ordering;

总结

三路比较运算符提高了比较的效率。如在类外可以直接通过通过三路比较运算符比较两个操作数的大小、等于关于关系,C++20前至少需要比较2次。同时,类内可以通过重载<=>运算符替代之前的6个操作符的重载及友元函数,极大的提高编码的效率。

欢迎关注公众号【程序员的园】