C++ 如何获取有关“的信息”;“当前类型”;在结构/类内部?

C++ 如何获取有关“的信息”;“当前类型”;在结构/类内部?,c++,macros,C++,Macros,是否可以在结构的内部获取“当前结构的类型”? 例如,我想做这样的事情: 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 {

是否可以在
结构的内部获取“当前
结构的类型”
? 例如,我想做这样的事情:

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

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

实际上,您可以使用类似这样的方法

#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);
};
#定义生成比较函数(类型,x,y)\
模板\
布尔运算符==(常量类型和t)常量\
{\
返回this->x==t.x&&this->y==t.y\
}
结构Foo
{
int x,y;
GEN_COMPARE_FUNC(Foo,x,y);
};

我不知道,如何使用Val.宏PARS(我们需要抛出PARAMS,并比较每个PAR和T,我不知道,如何在宏中扩展PARAMS).< /P> < P>这个堆栈溢出URL表示Boost库可以计算表达式的类型,但是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));
}
名称空间ex1
{
类型DEF增压_类型(1+0.5)类型;
BOOST_STATIC_ASSERT((is_same::value));
}

为什么不让您的宏genu\u COMPARE\u FUNC(foobar,x,y)代替?@永远通过
可变宏
。它由GCC和MSVC支持,所以对我来说已经足够了。通过使用模板化的
bool操作符==
,您可能会意外地使比较两种类型成为可能,而这两种类型之间的可比性是没有意义的。@Rollie,您是对的,当然可以通过这种方式实现。但是我需要确认没有其他的解决方案。我认为最接近的方法是在你想要使用宏的每个类中定义一个'curType',所以
typedef foobar curTypebool操作符==(const-curType&_-rhs)const{…}
C++11可以。typedef decltype(1+0.5)型;
namespace ex1
{
    typedef BOOST_TYPEOF(1 + 0.5) type;

    BOOST_STATIC_ASSERT((is_same<type, double>::value));
}