预处理器宏扩展到另一个预处理器指令
最初我认为我需要这个,但最终我避免了它。 然而,我的好奇心(以及对知识的渴望,嗯)让我问:
预处理器宏是否可以
#include "MyClass.h"
INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass)
扩展到另一个包含,例如
#include "MyClass.h"
#include "FooTemplate.h"
template class FooTemplate<MyClass>;
?
Initially I thought I needed this, but I eventually avoided it. However, my curiosity (and appetite for knowledge, hum) make me ask:
Can a preprocessor macro, for instance in
#include "MyClass.h"
INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass)
expand to another include, like in
#include "MyClass.h"
#include "FooTemplate.h"
template class FooTemplate<MyClass>;
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信这是不可能的,这是因为预处理器是单通道。 因此它不能发出其他预处理器指令。
具体来说,来自 C99 标准(6.10.3.4 第 3 段):
有趣的是,这就是为什么一元
_Pragma
运算符被添加到 c99 中。 因为#pragma
无法由宏发出,但_Pragma
可以。I believe that cannot be done, this is because the pre-processor is single pass. So it cannot emit other preprocessor directives.
Specifically, from the C99 Standard (6.10.3.4 paragraph 3):
Interestingly enough, This is why the unary
_Pragma
operator was added to c99. Because#pragma
could not be emited by macros, but_Pragma
can.C 标准对预处理指令有这样的规定(C99 - 6.10(2) - 预处理指令):
和 (C99 - 6.10(7)):
所以,不,宏不能扩展为“
#include
”预处理指令。 这些指令需要在翻译阶段 4 开始时就位(当处理这些指令时发生预处理)。 由于宏扩展发生在第 4 阶段,因此宏不能导致某些内容在第 4 阶段开始时存在。不过,我想指出,以下确实有效:
因为 C 标准说这(C99,6.10.2(4) - 源文件包含):
The C standard says this about preprocessing directives (C99 - 6.10(2) - Preprocessing directives):
and (C99 - 6.10(7)):
So, no, macros cannot expand into a '
#include
' preprocessing directive. Those directives need to be in place at the start of translation phase 4 (when handling those directives takes place preprocessing happens). Since macro expansion occurs during phase 4, macros can't cause something to exist at the start of phase 4.I'd like to point out however, that the following does work:
because the C standard says this (C99, 6.10.2(4) - Source file inclusion):
所有预处理器指令都会在宏扩展开始之前进行解释,因此不能将宏扩展为 #include 指令并对其进行这样的解释。 相反,它将被解释为(错误的)C++ 代码。
All preprocessor directives are interpreted before macro expansion begins, so no, you cannot have a macro expand into an #include directive and have it be interpreted as such. Instead, it will be interpreted as (erroneous) C++ code.