结构成员相等而不重载运算符== 在C++

Struct member equality without overloading operator== in C++

本文关键字:运算符 C++ 重载 成员 结构      更新时间:2023-10-16

是否可以定义某种模板来为结构创建通用的可比较运算符?

例如,这样的事情有可能吗?

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的解决方案。

是否可以定义某种模板来为结构创建通用的可比较运算符?

如果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 可以比较两个对象。

看看 https://github.com/apolukhin/magic_get。这个库可以为一些相当简单的结构自动生成比较运算符。

#include <iostream>
#include <boost/pfr/flat/global_ops.hpp>
struct S {
    char c;
    int i;
    double d;
};
int main() {
    S s1{'a', 1, 100.500};
    S s2 = s1;
    S s3{'a', 2, 100.500};
    std::cout << "s1 " << ((s1 == s2) ? "==" : "!=") << " s2n";
    std::cout << "s1 " << ((s1 == s3) ? "==" : "!=") << " s3n";
}
// Produces
// s1 == s2
// s1 != s3

你要求做的是遍历各种结构和比较成员是我的理解。

循环访问结构

这似乎不能用标准 c++ 来完成,但该线程提供了一些关于使用哪些库的想法。

从您的问题中不清楚所有结构是否具有相同的格式,我假设它们没有。