我只想编写一个操作符重载函数,但它可以执行==、!=、<=、<、>或>=。有没有可能我们可以使用预处理器来改变函数的符号?像这样的东西
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)
}
}对不起,我知道做像this.But这样的事情是不可能的,我只是好奇我是否可以写一个泛型运算符重载函数。
发布于 2020-05-16 00:24:15
C++20有一个宇宙飞船操作员,它将为你免费提供这个类的所有这些:
auto operator<=>(const A& obj) const = default;如果您的类更加复杂,以至于成员级比较还不够,那么您需要同时定义operator<=> (返回one of the _ordering types)和operator==,因为对于任何包含字符串或向量之类内容的类型,使用<=>进行非缺省相等很容易陷入性能陷阱。其他比较将被重写以使用这两个运算符。
这是一个full example
#include <cassert>
#include <compare>
struct A {
int b;
auto operator<=>(const A&) const = default;
};
struct B {
int b;
// This could return auto but this is an example.
std::strong_ordering operator<=>(const B& other) const {
return other.b <=> b;
}
bool operator==(const B& other) const {
return b == other.b;
}
};
int main() {
A a1{1}, a2{2};
assert(a1 < a2);
assert(a2 >= a1);
assert(a1 != a2);
B b1{1}, b2{2};
assert(b2 < b1);
assert(b1 >= b2);
assert(b1 != b2);
}发布于 2020-05-16 00:10:11
很好,您已经注意到它们的逻辑都非常相似--好眼力!
实际上,只编写一个运算符是很常见的,而且通常是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); }
};https://stackoverflow.com/questions/61823623
复制相似问题