是否可以定义某种模板来为结构创建通用的可比较运算符?
例如这样的事情可能吗?
struct A
{
int one;
int two;
int three;
};
bool AreEqual()
{
A a {1,2,3};
A b {1,2,3};
return ComparableStruct<A>(a) == ComparableStruct<A>(b);
}
所有这一切都是结构的逐个字段比较。您可以假设所有字段都是基本类型或具有重载的运算符==。
我有很多这样的结构,如果我可以将它放在模板或其他东西中进行比较,而不是为每个结构都定义一个运算符==,它会节省我很多时间。谢谢!
更新
C++ 似乎无法做到这一点。我想知道为什么这在 C++ 提案中被否决了,如果有人有理由告诉我们!
对于适用于基本类型的解决方案,请参见 R Sahu 的解决方案。
最佳答案
Is it possible to define some kind of template that can create a generic comparable operator for structs?
如果 struct
没有填充,您可以使用:
template <typename T>
struct ComparableStruct
{
ComparableStruct(T const& a) : a_(a) {}
bool operator==(ComparableStruct const& rhs) const
{
return (std::memcmp(reinterpret_cast<char const*>(&a_), reinterpret_cast<char const*>(&rhs.a_), sizeof(T)) == 0);
}
T const& a_;
};
更好的是,您可以使用函数模板。
template <typename T>
bool AreEqual(T cost& a, T const& b)
{
return (std::memcmp(reinterpret_cast<char const*>(&a), reinterpret_cast<char const*>(&b), sizeof(T)) == 0);
}
如果 struct
有任何填充,则不能保证使用 std::memcmp
可以比较两个对象。
关于c++ - 在 C++ 中不重载 operator== 的结构成员相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498881/