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

后端 未结 3 1219
眼角桃花
眼角桃花 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 14:14

    While in general ADL/KL is blessed way to go (kudos to Dietmar Kuhl), there is Curiously Recurring Template Pattern which might be used to facilitate such task (I've implemented not all methods, but idea is clear enough, I hope)

    template  struct B
    {
        bool operator==(const D& rhs) const { return !(rhs < *(const D*)this ) && !(*(const D*)this < rhs); }
        bool operator!=(const D& rhs) const { return !(*(const D*)this == rhs); }
    };
    
    struct D: public B
    {
        int _value;
    
        D(int value): _value(value) {}
    
        bool operator< (const D& rhs) const {return this->_value < rhs._value;}
    };
    
    int main()
    {
        D a(1);
        D b(2);
        D c(1);
    
        std::cout << (a == b) << " " << (a == c) << " " << (a != c) << std::endl;
    
        return 0;
    }
    

提交回复
热议问题