Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison operators in inherited classes

Tags:

c++

c++11

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?

like image 797
c.bear Avatar asked May 11 '18 13:05

c.bear


1 Answers

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

like image 197
YSC Avatar answered Oct 20 '22 01:10

YSC