General context
I have a self-made struct
and I want to compare two instance of it. In order to do that I obviously overload the operator==
so I will be able to do so. Now, this operator may be called with 0 to 2 const
instances and 0 to 2 non-const
instances.
As I want my operator ==
to compare 2 const as it compare any possible combination of const
and non-const
, the best for me should be to write only one overload which can deal with all possible combination. But as far as I know, I didn't find any way to do so.
Question
Does that mean that if I need to consider all possible combination, I have to write all 4 possible overloads ? Is there anyway I can avoid to write 4 times the same function only with const
keywords changing ?
Specific example
So here is the struct
. It represents an object on a plan, and consists of its position and a value associated to it:
struct Foo
{
int x;
int y;
double value;
};
Now let's say 2 Foo
are equal if they have the same value and the same position. I have the following operator:
inline bool operator==(Foo object) // Compare two non-const Foo
{
return (x == object.x) && (y == object.y) && (value == object.value);
}
But, eww, unlucky some Foo
can be constants, meaning that my objects can't move on the plan and can't change their value. And now I need to check if two const Foo
can be equals and if a non-const Foo
can be equal to a const Foo
.
Is there anyway I can do that but still avoid to write those following functions which are almost the same as the first one ?
inline bool operator==(const Foo &object) // Compare a non-const Foo with a const Foo
{
return (x == object.x) && (y == object.y) && (value == object.value);
}
inline bool operator==(const Foo &object) const // Compare two const Foo
{
return (x == object.x) && (y == object.y) && (value == object.value);
}
inline bool operator==(Foo object) const // Compare a const Foo with a non-const Foo
{
return (x == object.x) && (y == object.y) && (value == object.value);
}
I don't have any requirements on c++ version. It can ever be c++17 or c++20.