Comparing polymorphic types in c++20
As an intermediate solution you could re-factor your polymorphic equality operator==
to a non-virtual operator==
defined in the base class, which polymorphically dispatches to a non-operator virtual member function:
struct Identifier {
bool operator==(const Identifier& other) const {
return isEqual(other);
}
private:
virtual bool isEqual(const Identifier& other) const = 0;
};
// Note: do not derive this class further (less dyncasts may logically fail).
struct UserIdentifier final : public Identifier {
int userId = 0;
private:
virtual bool isEqual(const Identifier& other) const override {
const UserIdentifier *otherUser = dynamic_cast<const UserIdentifier*>(&other);
return otherUser && otherUser->userId == userId;
}
};
// Note: do not derive this class further (less dyncasts may logically fail).
struct MachineIdentifier final : public Identifier {
int machineId = 0;
private:
virtual bool isEqual(const Identifier& other) const override {
const MachineIdentifier *otherMachine = dynamic_cast<const MachineIdentifier*>(&other);
return otherMachine && otherMachine->machineId == machineId;
}
};
There will now no longer be an ambiguity as dispatch on the isEqual
virtual member function will always be done on the left hand side argument to operator==
.
const bool result = (user == machine); // user.isEqual(machine);