假设我有一个struct
包含多个数字字段的普通旧数据(POD)。
我想重载比较运算符,以便可以比较我的 POD 的两个实例。
问题是我需要对这些运算符(比如,运算符less()
)进行重载,以适应 POD 中的每个数字字段。
显然,下面的代码不起作用,因为编译器无法区分这两个版本:
struct my_struct{
int a;
int b;
int c;
};
bool operator<(const my_struct& one, const my_struct& two) {
return one.a < two.a;
}
bool operator<(const my_struct& one, const my_struct& two) {
return one.b < two.b;
}
因此,我编写了自己的自定义函数lessThan()
,它接受一个标志并执行该作业,但我并不特别喜欢这个解决方案(在下面的MWE中),因为我无法<
像使用比较运算符那样轻松地使用它。
#include <iostream>
#include <iomanip>
struct my_struct{
int a;
int b;
int c;
};
bool lessThan(const my_struct& one, const my_struct& two, const char flag) {
switch (flag) {
case 'a':
return one.a < two.a;
break;
case 'b':
return one.b < two.b;
break;
case 'c':
return one.c < two.c;
break;
default:
throw("Either case a, b, or c\n");
break;
}
}
int main()
{
my_struct one{1, 3, 4};
my_struct two{2, 2, 4};
std::cout << "one < two: " << std::boolalpha
<< lessThan(one, two, 'a') << std::endl;
return 0;
}
有没有办法以某种方式为struct
具有许多数值字段的自定义 POD 创建多个比较运算符重载,每个重载比较其中一个字段?
(为了给您提供更多背景信息,我需要这些重载来根据文件的任何特征对文件数组进行排序:例如按维度、按最后修改日期、按包含的文件或子目录的数量等。
在上面的简化示例中,每个 POD 实例抽象一个文件。)
编辑:
预期用途草图:
sortAccordingToFieldA(std::vector<my_struct>& my_vec, int a){
for (auto i : my_vec) {
for (auto j : [std::find(my_vec.begin(), my_vec.end(), i)+1, my_vec.end()] ) {
if (i < j) // here '<' is overloaded according to field 'a'
// sorting operations
}
}
}