结构的泛型比较运算符

Generic comparison operator for structs

本文关键字:运算符 比较 泛型 结构      更新时间:2023-10-16

在我的许多单元测试中,我需要比较只有数据成员的简单结构的内容:

struct Object {
int start;
int stop;
std::string message;
}

现在,如果我想写这样的东西:

CHECK(object1==object2);

我总是必须实现:

bool operator==(const Object& lhs, const Object& rhs) {
return lhs.start==rhs.start && lhs.stop==rhs.stop && lhs.message=rhs.message;
}

编写所有这些比较函数变得乏味,但也容易出错。试想一下,如果我向 Object 添加新的数据成员,但比较运算符不会更新,会发生什么。

然后我想起了我在 Haskell 和魔术deriving(Eq)指令中的知识,它只是免费生成一个理智的比较函数。

怎么,我能在C++中得出类似的东西?

令人高兴的是,我发现 C++17 带有一个通用operator==,并且每个结构都应该很容易转换为std::tuple借助std::make_tuple.

所以我大胆地尝试了以下几点:

#include <tuple>
#include <iostream>
#include <tuple>
template<typename T>
bool operator==(const T& lhs, const T& rhs)
{
auto leftTuple = std::make_tuple(lhs);
auto rightTuple = std::make_tuple(rhs);
return leftTuple==rightTuple;
}
struct Object
{
std::string s;
int i;
double d;
};
int main(int arg, char** args)
{
std::cout << (Object{ "H",1,2. } == Object{ "H",1,2. }) << std::endl;
std::cout << (Object{ "A",2,3. } ==  Object{ "H",1,2. }) << std::endl;
return EXIT_SUCCESS;
}

但是,不幸的是,它只是无法编译,我真的不知道为什么。叮当告诉我:

main.cpp:11:18: error: use of overloaded operator '==' is ambiguous (with operand types
'std::tuple<Object>' and 'std::tuple<Object>')
return leftTuple==rightTuple;

我可以修复此编译错误以获得我想要的行为吗?

不,因为比较元组恢复为比较元组的元素,所以leftTuple == rightTuple尝试比较两个Object,这是不可能的。

每个结构都应该很容易转换为std::tuple

,因为std::make_tuple

不,你只会得到一个带有一个元素的tuple,即结构。

诀窍是使用std::tie

std::tie(lhs.mem1, lhs.mem2) == std::tie(rhs.mem1, rhs.mem2)

但这与您的原始解决方案具有相同的问题。不幸的是,C++17 没有任何工具来避免这个问题,您可以编写宏:)。但是在 C++20 中,您将能够做到:

struct Object
{
std::string s;
int i;
double d;
bool operator==(const Object &) const = default;
};

这将为Object生成正确的比较运算符。