C++没有空格的宏
我需要一个宏来扩展为 C++ 注释,这可能吗?
我有这个:
#define SLASH(x,y) x y
#define OUT SLASH(/,/)
int main(int argc, char *argv[])
{
OUT << "text";
return 0;
}
并且需要扩展到这个:
{
// << "text";
return 0;
}
我也尝试过这个:
#define SLASH(x) /x
#define OUT SLASH(/)
但结果仍然是一样的:
int main(int argc, char *argv[])
{
/ / << "text";
return 0;
}
I need a macro to expand to a c++ comment, is that possible?
I've got this:
#define SLASH(x,y) x y
#define OUT SLASH(/,/)
int main(int argc, char *argv[])
{
OUT << "text";
return 0;
}
And need to expand to this:
{
// << "text";
return 0;
}
I've also tried this:
#define SLASH(x) /x
#define OUT SLASH(/)
But the result is still the same:
int main(int argc, char *argv[])
{
/ / << "text";
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,这是不可能的,因为在 C++ 中,注释在宏扩展之前被删除。
(参见标准的2.1,注释删除发生在第3阶段,宏扩展发生在第4阶段。)
No it's not possible because in C++ comments are removed before macros are expanded.
(See 2.1 of the standard, comment removal happens in phase 3, macro expansion in phase 4.)
将其替换为不执行任何操作的函数对象怎么样?
最终结果是该对象从代码中删除并被内联模板扩展替换,然后由于它们不执行任何操作而被优化。结果是绝对没有代码开销。
What about replacing it with a function object that does nothing instead?
The net result is that the object is removed from the code and replaced by inlined template expansions, that are then optimized out as they do nothing. Result is absolutely no code overhead.
正如其他人提到的,没有保证的方法可以定义您正在寻找的宏类型。实现与您似乎想要实现的结果类似的结果的其他方法是将输出语句包装在条件块中或定义仅丢弃所有输出的自定义输出流。这两种方法甚至可以组合起来,以便可以通过更改单个宏定义来切换行为。
As others mentioned there is no guaranteed way to define the kind of macro you are looking for. Other ways to achieve results that are similar to what you seem to be trying to achieve are wrapping your output statement in a conditional block or define a custom output stream that just discarded all output. The two approaches may even be combined so that behaviour could be switched by changing a single macro definition.
在预处理器运行之前,注释将从源代码中删除。所以你不能这样做。
Comments are removed from the source code before the preprocessor runs. So you cannot do this.
您想要实现的替代方案是:
http ://donjaffer.blogspot.in/2012/09/dprintf-debug-macro-in-c.html
无论您尝试在何处打印语句,而不是 COUT <<你可以使用
an alternate to what you want to achieve would be this :
http://donjaffer.blogspot.in/2012/09/dprintf-debug-macro-in-c.html
wherever you are trying to print the statements, instead of COUT << you can use