这段代码(容器遍历的宏)有效吗?如果是,为什么?
在 TopCoder 上的 Dmitry Korolev 教程之后,我遇到了这个 generic-container-traverse 宏:
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
它让我感到困惑,因为它似乎缺少括号。在解释中他说 typeof(...) 被表达式 (...) 的类型替换,这让我对这个遍历宏更加困惑(因为我的直觉看到 typeof (x ; y ; z) 和不会 工作,因为 x;y;z 不是一个表达式,即使它工作 typeof(...) 也会“吃掉” (...))。
有效吗?为什么?
Following Dmitry Korolev tutorial on TopCoder i encountered this generic-container-traverse macro:
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
It confuses me because it appears to be missing a parenthesis. And in the explanation he says that typeof(...) is replaced by the type of the expression (...) , which makes me more confused with this traverse macro (since my intuition sees typeof (x ; y ; z) and would not
work since x;y;z is not a expression and even if it worked typeof(...) would "eat" the (...)).
Does it work? why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是他写的,语法上是正确的。 BTW
typeof
是一个 gcc 扩展,不能在其他编译器中工作。如果您的编译器支持 C++0x,您可能需要使用
auto
例如,相同的宏可以在 C++0x 中编写为
This is what he has written which is syntactically correct. BTW
typeof
is a gcc extension and won't work in other compilers.If your compiler supports C++0x you might want to use
auto
For example the same macro can be written in C++0x as
这是一个错字。应该是:
It's a typo. Should be:
如果
typeof((c).begin()
之后有一个额外的括号,那就可以了。我不知道原始来源是什么,但如果它实际上缺少一个括号,那么原始的放置它的人可能输入错误。可以用来代替容器上的 for 循环的顶行,例如:
It would work fine if there was an extra paren after
typeof((c).begin()
. I don't know what the original source was, but if it was actually missing a paren, the original person who put it probably typed it wrong.Can be used in place of the top line of a for loop over a container. eg:
这是错误的。应该是:
This is wrong. It should be: