如果结构具有任意多个数据成员(<使用数据成员的列出顺序进行定义),如何推广>
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;
}
};
以某种方式使用可变参数模板和递归?
可以使用
std::tie
创建对类成员的引用元组,并使用为元组定义的字典顺序比较运算符:
bool operator < (const nData& other) const { // better make it const
return std::tie(a,b,c) < std::tie(other.a, other.b, other.c);
}
这种结构很容易扩展,并允许使用任意比较函数(例如 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;