Wow, many other answers were so completely unnecessary. dynamic_cast - it exists, use it.
class Animal { public: virtual bool operator==(const Animal& other) = 0; virtual ~Animal() = 0; }; template<class T> class AnimalComp : public Animal { public: virtual bool operator==(const Animal& ref) const { if (const T* self = dynamic_cast<const T*>(&ref)) { return ((T*)this)->operator==(*self); } return false; } virtual bool operator!=(const Animal& ref) const { if (const T* self = dynamic_cast<const T*>(&ref)) { return ((T*)this)->operator!=(*self); } return true; } }; class Monkey : public AnimalComp<Monkey> { public: virtual bool operator==(const Monkey& other) const { return false; } virtual bool operator!=(const Monkey& other) const { return false; } }; class Snake : public AnimalComp<Snake> { public: virtual bool operator==(const Snake& other) const { return false; } virtual bool operator!=(const Snake& other) const { return false; } };
Edit: Worship my automatic template customization!
Editing editing. One thing I did was forget to mark them as const, which was not the case. I wonβt apologize for what Iβm not doing! = How, let him face it, realizing it - this is a complete failure.
More rights: guys from Jesus Christ, this is not an example of how to write! = Or ==, this is an example of how to use CRTP. If you do not like how I decided to implement mine! = Or ==, you can sue.
Puppy
source share