How to generalize the definition of < if the struct has arbitrarily many data members (< is to be defined using the order in which the data members are listed)? A simple example with 3 data members:
struct nData {
int a;
double b;
CustomClass c; // with == and < defined for CustomClass
bool operator == (const nData& other) {return (a == other.a) && (b == other.b) && (c == other.c);}
bool operator < (const nData& other) {
if ( (a < other.a) || ((a == other.a) && (b < other.b)) ||
((a == other.a) && (b == other.b) && (c < other.c)) )
return true;
return false;
}
};
Using variadic templates and recursion somehow?
You can use std::tie
to create a tuple of references to the class members, and use the lexicographical comparison operators defined for tuples:
bool operator < (const nData& other) const { // better make it const
return std::tie(a,b,c) < std::tie(other.a, other.b, other.c);
}
This structure scales easily, and allows using arbitrary comparison functions (e.g. strcmp
)
if (a != other.a) return a < other.a;
if (b != other.b) return b < other.b;
if (c != other.c) return c < other.c;
return false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With