C++宏“如果定义了类”

发布于 2024-08-29 17:55:32 字数 106 浏览 4 评论 0原文

C++ 中是否有这样的宏(交叉编译器或特定于编译器):

#if isclass(NameSpace::MyClass)

会很有用。

Is there such macro in C++ (cross-compiler or compiler-specific):

#if isclass(NameSpace::MyClass)

Would be useful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

酒废 2024-09-05 17:55:32

不会。预处理指令和宏由预处理器计算,预处理器在代码被解析为 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.

看轻我的陪伴 2024-09-05 17:55:32

如果您不关心可移植性,则 __if_exists VC++中的语句满足您的需求。

If you do not care about portability, the __if_exists statement in VC++ meets your needs.

笑着哭最痛 2024-09-05 17:55:32

预处理阶段没有这个东西,所以没有宏。

但是,您可以查看 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.

甜心 2024-09-05 17:55:32

这是不可能的,但您可以使用 include Guard 常量来验证该类是否已包含在内。

That's not possible, but you could use your include guard constant to verify that the class has been included.

ぶ宁プ宁ぶ 2024-09-05 17:55:32

在我看来,最好测试一下包含您要查找的类定义的头文件是否已包含在内,而不是尝试查看该类是否存在。如果您一直在实现为每个头文件定义符号的标准,那么检查这一点确实很容易,如下所示:

// myfile.h

#ifndef _MYFILE_H_
#define _MYFILE_H_

// CODE

#endif // _MYFILE_H_

不过,最好的选择是首先确保头文件以正确的顺序包含在其中。最简单的方法是拥有一个“整体”头文件,该文件又以正确的顺序包含您需要的所有头文件。只需将其包含在项目的每个源文件中,就可以开始了。这不一定是最好的解决方案,但它是最简单的。

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:

// myfile.h

#ifndef _MYFILE_H_
#define _MYFILE_H_

// CODE

#endif // _MYFILE_H_

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文