使用GCC编译没有RTTI的时间类型 [英] Compile time typeid without RTTI with GCC

查看:385
本文介绍了使用GCC编译没有RTTI的时间类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否还有从RTCC禁用GCC的编译时获取编译时 typeid 信息?在Visual Studio下,一个简单的命令如 const char * typeName = typeid(int).name(); 将适当地返回int,即使RTTI被禁用。不幸的是,GCC不能这样做。当我尝试调用 typeid 没有RTTI,我的程序崩溃。我知道禁用RTTI不是标准的一部分,但是有没有我可以强制GCC做编译时解决已知类型?

Is there anyway to get compile-time typeid information from GCC with RTTI disabled? Under Visual Studio, a simple command like const char* typeName = typeid(int).name(); will appropriately return "int", even if RTTI is disabled. Unfortunately, GCC can't do the same. When I try to call typeid without RTTI, my program crashes. I know disabling RTTI is not part of the standard, but is there anyway I can force GCC to do compile time resolution of known types?

RTTI被禁用为性能原因。我不需要运行时RTTI。

RTTI is disabled for performance reasons. I have no need for runtime RTTI.

编辑:

p>

Here's what I ended up going with:

template<typename T> const char* TypeName(void);
template<typename T> const char* TypeName(T type) { return TypeName<T>(); }

#define REFLECTION_REGISTER_TYPE(type) \
    template <> const char* TypeName<type>(void) { return #type; } 

它需要调用 REFLECTION_REGISTER_TYPE 每种类型都需要反射信息。但是只要调用每个必需的类型,调用 TypeName< int> 就可以很好地工作。我还添加了 TypeName(T type)这意味着你可以这样做: int x = 0; printf(TypeName(x)); ,它将打印出int。 GCC应该真的能够在编译时这样做像VC ++可以。

It requires that REFLECTION_REGISTER_TYPE be called for every type that needs reflection info. But as long as it's called for every required type, calling TypeName<int> works perfectly. I also added the function TypeName(T type) which means you can do things like this: int x = 0; printf(TypeName(x)); and it will print out "int". GCC should really be able to do this at compile time like VC++ can.

推荐答案

否。 RTTI是 RunTime 类型信息(并禁用它是愚蠢的,但嘿),这是 typeid 的目的。如果你想在编译时对类型名称进行字符串化,你必须自己做(通过模板或者宏)。

No. RTTI is RunTime Type Information (and disabling it is silly, but hey), and that's the purpose of typeid. If you want to stringise type names at compile time, you have to do it yourself (via template or macros).

这篇关于使用GCC编译没有RTTI的时间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆