我想以通用的方式比较结构,我已经做了这样的事情(我不能分享实际的来源,所以如果有必要,请询问更多细节):
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::string
、 std::vector
和许多其他)。
关于c++ - 如何比较 C++ 中的泛型结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079990/