如何获取有关结构/类内部"current type"的信息?

How to get information about "current type" inside of a struct/class?

本文关键字:内部 current type 信息 结构 何获取 获取      更新时间:2023-10-16

是否可以在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;
  }
}

我试着这样做:

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;
  }
}

但它看起来很难看,需要支持最新的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);
}

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

实际上,您可以使用这样的k。

#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);
};

我不知道如何以这种方式使用var.macon-pars(我们需要抛出params,并比较来自this和t的每个par,我不知道,如何在宏中扩展params)。

这个堆栈溢出URL声明boost库可以计算表达式的类型,但C/C++本身不能:

从对象中获取结构字段的名称和类型

有人也提出了类似的问题:

如何向C++应用程序添加反射?

要开始使用typeof,请包括typeof标头:

#include <boost/typeof/typeof.hpp>

要在编译时推导表达式的类型,请使用BOOST_TYPEOF宏:

namespace ex1
{
    typedef BOOST_TYPEOF(1 + 0.5) type;
    BOOST_STATIC_ASSERT((is_same<type, double>::value));
}