Define generic comparison operator

前端 未结 4 2033
[愿得一人]
[愿得一人] 2021-01-07 19:22

I came up with the idea to define a generic comparison operator which would work with any type, for the fun of it.

#include 
#include 

        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 20:10

    As a slight aside, the nicest way I know of writing equality operators for classes with lots of members uses this idea (this code requires C++ 14):

    #include 
    
    struct foo
    {
        int x    = 1;
        double y = 42.0;
        char z   = 'z';
    
        auto
        members() const
        {
            return std::tie(x, y, z);
        }
    };
    
    inline bool
    operator==(const foo& lhs, const foo& rhs)
    {
        return lhs.members() == rhs.members();
    }
    
    int
    main()
    {
        foo f1;
        foo f2;
    
        return f1 == f2;
    }
    

    Code on Compiler Explorer

提交回复
热议问题