Comparison operators in inherited classes

  • A+
Category:Languages

I've defined an IntWrapper class like the following one:

struct IntWrapper { protected:   int value;  public:   explicit IntWrapper() = default;   explicit IntWrapper(const int value) : value(value) {}    bool operator< (const IntWrapper rhs) const { return value <  rhs.value; }   bool operator> (const IntWrapper rhs) const { return value >  rhs.value; }   bool operator<=(const IntWrapper rhs) const { return value <= rhs.value; }   bool operator>=(const IntWrapper rhs) const { return value >= rhs.value; }   bool operator==(const IntWrapper rhs) const { return value == rhs.value; }    explicit operator int() const { return value; } }; 

and the classes Foo and Bar that inherit from IntWrapper

struct Foo: IntWrapper {   using IntWrapper::IntWrapper; };  struct Bar: IntWrapper {   using IntWrapper::IntWrapper; }; 

I'd like to compare only objects of the same type. In other words I'd like the following piece give compilation error, instead of casting foo and bar to IntWrapper.

const Foo foo(1); const Bar bar(2); bool b = foo >= bar; 

Since I have many other objects like Foo and Bar, in there any way to achieve my result keeping all the comparison operators inside IntWrapper?


You can add a dummy template to your IntWrapper to make the comparison operators work for same-type IntWrapper only:

template<class> struct IntWrapper { /* same code */ };  struct Foo : IntWrapper<Foo> { using IntWrapper::IntWrapper; }; struct Bar : IntWrapper<Bar> { using IntWrapper::IntWrapper; };  int main() {     const Foo foo(1);     const Bar bar(2);     //bool b = foo >= bar; // error: no match for 'operator>=' (operand types are 'const Foo' and 'const Bar') } 

live demo

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: