Convenient way to define all comparison operators for class with one numeric data member?

后端 未结 3 1261
眼角桃花
眼角桃花 2021-01-13 13:08

If I have a type that consists of a single numeric data member (say, an int) and various methods, is there a convenient way to tell the compiler to automaticall

3条回答
  •  情书的邮戳
    2021-01-13 13:54

    The C++ way of doing this is to use a tag type and ADL. Here is a quick example:

    namespace relational {
        struct tag {};
    
        template 
        bool operator== (T const& lhs, T const& rhs) { return !(rhs < lhs) && !(lhs < rhs); }
        template 
        bool operator!= (T const& lhs, T const& rhs) { return !(lhs == rhs); }
    
        template 
        bool operator> (T const& lhs, T const& rhs) { return rhs < lhs; }
        template 
        bool operator<= (T const& lhs, T const& rhs) { return !(rhs < lhs); }
        template 
        bool operator>= (T const& lhs, T const& rhs) { return !(lhs < rhs); }
    }
    
    struct foo: relational::tag {
        int value;
        foo(int value): value(value) {}
        bool operator< (foo const& other) const { return this->value < other.value; }
    };
    
    #include 
    void compare(foo f0, foo f1) {
        std::cout << std::boolalpha
                  << f0.value << " == " << f1.value << " => " << (f0 == f1) << '\n'
                  << f0.value << " != " << f1.value << " => " << (f0 != f1) << '\n'
                  << f0.value << " <  " << f1.value << " => " << (f0 <  f1) << '\n'
                  << f0.value << " <= " << f1.value << " => " << (f0 <= f1) << '\n'
                  << f0.value << " >  " << f1.value << " => " << (f0 >  f1) << '\n'
                  << f0.value << " >= " << f1.value << " => " << (f0 >= f1) << '\n'
            ;
    }
    int main() {
        compare(foo(1), foo(2));
        compare(foo(2), foo(2));
    }
    

提交回复
热议问题