我只想编写一个运算符重载函数,但是它可以执行==,!=,<=,或> =。是否可以使用预处理器更改函数的符号?像这样的东西
class A{
private:
int b;
//some code
public:
#define macro(sign) sign
bool operator macro(sign)(const A& obj){
return (b macro(sign) obj.b)
}
}
对不起,我知道这样做是不可能的。但是我很好奇我是否可以编写泛型运算符重载函数。
很好,您已经注意到他们所有的逻辑都非常相似-好的眼睛!
实际上,通常只写一个运算符,通常是operator<
。然后,我们可以在其他任何地方使用它。因此,您的实现可能看起来像:
class A {
bool operator<(const A& rhs) const {
// Custom comparison logic here...
}
bool operator>(const A& rhs) const { return rhs < *this; }
bool operator<=(const A& rhs) const { return !(rhs < *this); }
bool operator>=(const A& rhs) const { return !(*this < rhs); }
bool operator==(const A& rhs) const { return !(*this < rhs) && !(rhs < *this); }
bool operator!=(const A& rhs) const { return (*this < rhs) || (rhs < *this); }
};
C ++ 20有一个太空飞船操作员,它将为您免费为此类提供所有这些:
auto operator<=>(const A& obj) const = default;
[如果您的类更复杂,以致于逐成员比较不足够,则需要定义operator<=>
(返回one of the _ordering
types)和_ordering
,因为使用operator==
进行非默认相等很容易到任何包含字符串或向量之类的类型的性能陷阱中。其他比较将被重写为使用这两个运算符。
这里是<=>
:
full example