有没有办法计算#define 术语?
#define BLAH word
cout << BLAH;
有什么办法可以做到这一点吗?
#define BLAH word
cout << BLAH;
Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
#define BLAH word
cout << BLAH;
有什么办法可以做到这一点吗?
#define BLAH word
cout << BLAH;
Is there any way to do this?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
Try
额外的间接级别会导致宏的值而不是宏的名称被字符串化。
在 ideone 上测试。
Try
The extra level of indirection causes the value of the macro to be stringified instead of the name of the macro.
Tested on ideone.
“cout”不是你做的事情。它是一个全局变量,是
std::ostream
类型的实例。您可以说“输出到cout
”。#define
进行文本替换。它基本上与您在文本编辑器中使用搜索和替换将BLAH
替换为word
相同。因此,行cout << BLAH;
变成cout <<词;
。如果它不起作用,那是因为cout << word;
不是该范围内的有效语句。预处理器不关心任何周围的文本。它对代码的理解基本上为零(它知道如何标记代码,即如果您不输入任何空格,则将运算符和其他标点符号分开,但仅此而已。)'cout' is not something you do. It is a global variable, which is an instance of the
std::ostream
type. You could say e.g. "output tocout
".#define
does textual substitution. It is basically the same as if you used search-and-replace in your text editor to replaceBLAH
withword
. Thus, the linecout << BLAH;
turns intocout << word;
. If it's not working, it's becausecout << word;
isn't a valid statement in that scope. The preprocessor does not care about any of the surrounding text. It has basically zero understanding of the code (it knows how to tokenize the code, i.e. break apart operators and other punctuation if you don't put in any space, but that's about it.)如果你想打印单词
“word”
,你可以这样做:If you want to print the word
"word"
, you can do:我怀疑您想要这样的东西:
请注意,
typeid(T).name()
的值是实现定义的,并且可能什么都没有。如果不自己为每种类型编写函数,就无法以有保证的方式打印出类型。您也可以进行重载来推断表达式的类型:(
请注意,这会计算表达式,这是不必要的,但我怀疑这是一个问题。)
I suspect you want something like this:
Note that value of
typeid(T).name()
is implementation defined, and may be nothing at all. There is no way to print out a type in a guaranteed way without writing a function yourself, for each type.You can make an overload that deduces the type of the expression too:
(Note that this evaluates the expression, which is unnecessary, but I doubt that is a concern.)
无需滥用宏作为原始 typedef:
请注意,这可以让您为每个测试指定不同的名称(希望更有意义),而不仅仅是将测试的参数字符串化,但“float”和“double”可以是名称,如果您喜欢。
如果您真的非常想对参数进行字符串化,或者您只是对宏感到好奇:
No need to abuse macros as a primitive typedef:
Notice this lets you give different names (hopefully more meaningful) to each test, rather than just stringizing the parameters to the test, but "float" and "double" could be the names if you like.
If you really, really wanted to stringize the parameters – or if you're just curious about macros:
好的,让我们根据您的评论再试一次:
听起来这就是你真正的意思:
在这种情况下,你想要这样的东西:
OK, let's try this again, based on your comment:
It sounds like this is what you really mean:
In that case, you want something like this: