如何获取有关结构/类内部"current type"的信息?
How to get information about "current type" inside of a struct/class?
是否可以在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));
}
相关文章:
- 将函数类成员映射到类本身内部
- Boost Spirit,获取迭代器内部语义动作
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 内联函数中具有内部链接的全局变量
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 卷曲bracers内部结构的声明
- 从函数角度看ID到文件路径的内部与外部映射
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 如何在pugixml中获取节点的内部XML
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- 方法内部但循环仍得到预期的不合格id错误C++
- C++:具有内部链接的正向声明常量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- libcurl 和 DNS ttl 中的内部连接管理
- 如何修改 lambda 内部字符串的向量
- 如果我将嵌套映射作为多重映射的值,如何将值插入内部映射?
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 如何获取有关结构/类内部"current type"的信息?