首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有可能预处理器可以改变操作符重载函数的符号?

有没有可能预处理器可以改变操作符重载函数的符号?
EN

Stack Overflow用户
提问于 2020-05-16 00:05:47
回答 2查看 50关注 0票数 0

我只想编写一个操作符重载函数,但它可以执行==、!=、<=、<、>或>=。有没有可能我们可以使用预处理器来改变函数的符号?像这样的东西

代码语言:javascript
运行
复制
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这样的事情是不可能的,我只是好奇我是否可以写一个泛型运算符重载函数。

EN

回答 2

Stack Overflow用户

发布于 2020-05-16 00:24:15

C++20有一个宇宙飞船操作员,它将为你免费提供这个类的所有这些:

代码语言:javascript
运行
复制
auto operator<=>(const A& obj) const = default;

如果您的类更加复杂,以至于成员级比较还不够,那么您需要同时定义operator<=> (返回one of the _ordering types)和operator==,因为对于任何包含字符串或向量之类内容的类型,使用<=>进行非缺省相等很容易陷入性能陷阱。其他比较将被重写以使用这两个运算符。

这是一个full example

代码语言:javascript
运行
复制
#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);
}
票数 2
EN

Stack Overflow用户

发布于 2020-05-16 00:10:11

很好,您已经注意到它们的逻辑都非常相似--好眼力!

实际上,只编写一个运算符是很常见的,而且通常是operator<。然后我们可以在其他地方使用它。因此,您的实现可能如下所示:

代码语言:javascript
运行
复制
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); }
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61823623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档