C++宏“如果定义了类”
C++ 中是否有这样的宏(交叉编译器或特定于编译器):
#if isclass(NameSpace::MyClass)
会很有用。
Is there such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不会。预处理指令和宏由预处理器计算,预处理器在代码被解析为 C++ 之前完成其任务。预处理器不了解类或命名空间。
No. Preprocessing directives and macros are evaluated by the preprocessor, which completes its tasks before the code is parsed as C++. The preprocessor has no knowledge of classes or namespaces.
如果您不关心可移植性,则 __if_exists VC++中的语句满足您的需求。
If you do not care about portability, the __if_exists statement in VC++ meets your needs.
预处理阶段没有这个东西,所以没有宏。
但是,您可以查看
is_class
类型特征 可在 Boost 或 C++0x 中使用,使您能够在编译时做出决定。There is no such thing at the preprocessing stage, so no macro.
However you can have a look at the
is_class
type traits available in Boost or in C++0x that enable you to take decisions at compile time.这是不可能的,但您可以使用 include Guard 常量来验证该类是否已包含在内。
That's not possible, but you could use your include guard constant to verify that the class has been included.
在我看来,最好测试一下包含您要查找的类定义的头文件是否已包含在内,而不是尝试查看该类是否存在。如果您一直在实现为每个头文件定义符号的标准,那么检查这一点确实很容易,如下所示:
不过,最好的选择是首先确保头文件以正确的顺序包含在其中。最简单的方法是拥有一个“整体”头文件,该文件又以正确的顺序包含您需要的所有头文件。只需将其包含在项目的每个源文件中,就可以开始了。这不一定是最好的解决方案,但它是最简单的。
It sounds to me like it would be better to test if the header file with the class definition you're looking for has been included yet, instead of trying to see if the class exists. It's really easy to check this if you've been implementing the standard of defining a symbol for each header file, as shown:
Your best bet though, is to just make sure your header files are being included in the right order in the first place. The easiest way to do this is to have an "overall" header file that in turn includes all the headers you will need in the correct order. Simply include that in each of the source files in your project, and you'll be good to go. This isn't necessarily the best solution, but it is the easiest.