Simpler way to compare objects
Say I have Person:
struct Person
{
int age;
double height;
double weight;
std::string name;
}
My comparator is quite ugly and looks like:
bool operator==(const Person & a, const Person & b)
{
if(a.age != b.age) return false;
if(a.height != b.height) return false;
if(a.weight != b.weight) return false;
if(a.name != b.name) return false;
return true;
}
Is it possible to rewrite it in a format that looks more like:
bool operator==(const Person & a, const Person & b)
{
for(auto field : {age, height, weight, name})
if(a.field != b.field) return false;
return true;
}
Seems more readable, modern and extendable. What is the closest I can get to something like the bottom set of code?
Posted Apr 1, 2019, 10:30 PM UTC
One neater way is
Thanks for the response. I do quite like that but my real example has a lot of fields, so it looks a bit unruly and unmanageable having like 4 lines of things that should match. I have changed the code to be:
This way I only need to add new members on the one line and I get them for free.