c++ - 如何比较 C++ 中的泛型结构?

标签 c++ templates struct padding memcmp

我想以通用的方式比较结构,我已经做了这样的事情(我不能分享实际的来源,所以如果有必要,请询问更多细节):

template<typename Data>
bool structCmp(Data data1, Data data2)
{
  void* dataStart1 = (std::uint8_t*)&data1;
  void* dataStart2 = (std::uint8_t*)&data2;
  return memcmp(dataStart1, dataStart2, sizeof(Data)) == 0;
}

这主要按预期工作,但有时即使两个 struct 实例具有相同的成员(我已经使用 eclipse 调试器检查过),它也会返回 false。经过一番搜索,我发现 memcmp由于使用的结构被填充,可能会失败。

有没有更合适的方法来比较对填充无动于衷的内存?我无法修改使用的结构(它们是我正在使用的 API 的一部分),并且使用的许多不同结构具有一些不同的成员,因此无法以通用方式单独比较(据我所知)。

编辑:不幸的是,我被 C++11 困住了。应该早点提到这个...

最佳答案

你是对的,填充会妨碍你以这种方式比较任意类型。

您可以采取以下措施:

  • 如果您控制了 Data然后例如 gcc 有 __attribute__((packed)) .它对性能有影响,但可能值得一试。尽管如此,我不得不承认我不知道packed使您能够完全禁止填充。 Gcc doc说:

  • This attribute, attached to struct or union type definition, specifies that each member of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.


  • 如果您无法控制 Data那么至少 std::has_unique_object_representations<T> 可以告诉您您的比较是否会产生正确的结果:

  • If T is TriviallyCopyable and if any two objects of type T with the same value have the same object representation, provides the member constant value equal true. For any other type, value is false.



    并进一步:

    This trait was introduced to make it possible to determine whether a type can be correctly hashed by hashing its object representation as a byte array.



    PS:我只解决了填充问题,但不要忘记,对于内存中具有不同表示形式的实例,可以比较相等的类型绝非罕见(例如 std::stringstd::vector 和许多其他)。

    关于c++ - 如何比较 C++ 中的泛型结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079990/

    相关文章:

    struct - 使用单个引用传递结构是否有任何隐藏成本?

    c++ - 围绕标量初始值设定项错误的大括号

    c - 访问结构数组时发生内存冲突

    c++ - 将 lambda 中捕获的 const 值用作模板参数是否合法?

    c++如何按每行列中的值对二维 vector 的行进行排序

    c++ - 在 C++ 中重载模板类的 [] 运算符,get 和 set

    c++ - 如何避免 expr 中的溢出。 A B C D

    c++ - 带有模板参数的模板中的默认值 (C++)

    c++ - 将函数作为显式模板参数传递

    c++ - 是否可以合法地重载字符串文字和 const char*?