C ++结构的自动比较器

c++ auto-comparator for structs

有许多原始结构(数百个),用于在两个组件(例如播放器和服务器)之间传输数据。其中没有方法,只有原始数据。 任务是编写所有请求和答案,以便能够在没有服务器的情况下重播玩家场景(我们记住所有问题和所有答案,它们都是纯函数)。 所以任务是将这个结构放在没有比较器的映射中。现在我们使用memcmp,它允许不考虑这个结构的变化并且它是紧凑的,但是padding等问题太多

是否有可能获得类似 getHashValue 或任何默认比较器的 smth,使用 C++ 中的元编程? 状况: 1) 我不想为每个结构创建一个比较器。 2)如果添加或删除字段破坏了现有行为并需要修复,我希望出现错误。 3) 我不想更改带有结构定义的头文件。

结构示例

struct A {
  int a;
  int b;
  c c;
}

bool operator<(const A& a1, const A& a2)
{
  if (a1.a != a2.a) return a1.a < a2.a;
  if (a1.b != a2.b) return a1.b < a2.b;
  if (a1.c != a2.c) return a1.c < a2.c;
  return false;
} 

我可以考虑使用其他语言来实现这个确切的部分(收集 questions/answers),如果它不需要再次用该语言描述所有这些结构。

我想您可以根据 memcmp.

编写自己的比较运算符
bool operator<(const A &lhs, const A &rhs) {
    return memcmp(&lhs, &rhs, sizeof(A)) < 0;
}

当然,为每个对象编写这些可能是一种负担,因此您可以为此编写一个模板。虽然没有一些 SFINAE 它将覆盖太多类型。

 #include <type_traits>
 #include <cstring>

 template<typename T>
 std::enable_if_t<std::is_pod_v<std::decay_t<T>      //< Check if POD
                  && !std::is_fundamental_v<std::decay_t<T>>>, //< Don't override for fundamental types like 'int'
     bool>
     operator<(const T &lhs, const T &rhs) {
     return memcmp(&lhs, &rhs, sizeof(std::decay_t<T>)) < 0;
 }

编辑:请注意,此技术要求您对结构进行零初始化。

看起来最好的方法是编写一个生成器,它将使用 bool operator< 为该头文件中的所有类型生成 .h 和 .cpp。然后将此项目作为预构建步骤添加到 main.

它看起来不是一个很好的解决方案,但它可以避免手写代码重复并将支持 adding/removing 新 structs/fields。所以没找到更好的方法。

在 C++17 中,如果您愿意 (A) 在某处对每个结构中的元素数量进行硬编码,并且 (B) 为每个结构中的元素数量编写或生成代码,则可以完成此操作结构。

template<std::size_t N>
using size_k = std::integral_constant<std::size_t, N>;

template<class T>
auto auto_tie( size_k<0>, T&& t ) {
  return std::tie();
}
template<class T>
auto auto_tie( size_k<1>, T&& t ) {
  auto& [ x0 ] = std::forward<T>(t);
  return std::tie( x0 );
}
template<class T>
auto auto_tie( size_k<2>, T&& t ) {
  auto& [ x0, x1 ] = std::forward<T>(t);
  return std::tie( x0, x1 );
}
// etc

现在,在相关结构的命名空间中,写入

struct foo {
  int x;
};
struct bar {
  int a, b;
};
size_k<1> elems( foo const& ) { return {}; }
size_k<2> elems( bar const& ) { return {}; }

一个 elems 函数 return size_k 计算元素的数量。

现在在结构的命名空间中,写:

template<class T, class Size=decltype(elems(std::declval<T const&>()))>
bool operator<( T const& lhs, T const& rhs ) {
  return auto_tie( Size{}, lhs ) < auto_tie( Size{}, rhs );
}

大功告成。

测试代码:

foo f0{1}, f1{2};
bar b0{1,2}, b1{-7, -3};

std::cout << (f0<f1) << (f1<f0) << (f0<f0) << "\n";
std::cout << (b0<b1) << (b1<b0) << (b0<b0) << "\n";

Live example.

比这更进一步将需要编写第 3 方工具或等待对 C++ 的反射扩展,可能在 C++20 或 23 中。

如果 elems 错误,我相信 auto_tie 中的结构化绑定代码应该会产生错误。