如何在struct/class中获取有关"当前类型"的信息?

qeh*_*hgt 5 c++ macros

是否有可能获得"当前的类型struct" struct?例如,我想做这样的事情:

struct foobar {
  int x, y;

  bool operator==(const THIS_TYPE& other) const  /*  What should I put here instead of THIS_TYPE? */
  {
    return x==other.x && y==other.y;
  }
}
Run Code Online (Sandbox Code Playgroud)

我试着这样做:

struct foobar {
  int x, y;

  template<typename T>
  bool operator==(const T& t) const
  {
    decltype (*this)& other = t; /* We can use `this` here, so we can get "current type"*/
    return x==other.x && y==other.y;
  }
}
Run Code Online (Sandbox Code Playgroud)

但它看起来很难看,需要支持最新的C++标准,而MSVC不能编译它(它会因"内部错误"而崩溃).

实际上,我只是想编写一些预处理器宏来自动生成如下函数operator==:

struct foobar {
  int x, y;
  GEN_COMPARE_FUNC(x, y);
}

struct some_info {
  double len;
  double age;
  int rank;
  GEN_COMPARE_FUNC(len, age, rank);
}
Run Code Online (Sandbox Code Playgroud)

但我需要知道宏内部的"当前类型".

For*_*veR 0

实际上,你可以使用类似这样的想法。

#define GEN_COMPARE_FUNC(type, x, y)\
template<typename type>\
bool operator ==(const type& t) const\
{\
    return this->x == t.x && this->y == t.y;\
}

struct Foo
{
    int x, y;
    GEN_COMPARE_FUNC(Foo, x, y);
};
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用 var。以这种方式宏参数(我们需要抛出参数并比较此参数和 t 中的每个参数,我不知道如何在宏中扩展参数)。