C++ assert:断言宏中表达式的优先级 [英] C++ assert: the precedence of the expression in an assert macro

查看:38
本文介绍了C++ assert:断言宏中表达式的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中:

  assert(  std::is_same<int , int>::value  ); // does not compile

  assert( (std::is_same<int , int>::value) ); // compiles

谁能解释一下为什么?

推荐答案

逗号被视为宏的参数分隔符,但第二种情况下的括号保护参数.我们可以通过转到 C++ 标准草案部分16.3 宏替换来看到这一点,其中说(强调我的):

The comma is being treated as a argument separator for the macro, but parenthesis in your second case protect the arguments. We can see this by going to the draft C++ standard section 16.3 Macro replacement which says (emphasis mine):

由最外层限定的预处理标记序列匹配括号形成类似函数的参数列表宏.列表中的各个参数用逗号分隔预处理标记,但匹配之间的逗号预处理标记内括号不分隔参数.如果有预处理参数列表中的标记,否则作为预处理指令,154 行为未定义

The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives,154 the behavior is undefined

通过转到2.2翻译阶段,我们可以看到宏扩展发生在语义分析之前,并看到第 4 阶段是包括:

We can see that macro expansion happens before semantic analysis by going to section 2.2 Phases of translation and see that phase 4 is includes:

执行预处理指令,扩展宏调用,[...] 然后删除所有预处理指令.

Preprocessing directives are executed, macro invocations are expanded, and [...] All preprocessing directives are then deleted.

和第 7 阶段包括:

[...]每个预处理标记被转换成一个标记.(2.7).这结果标记在句法和语义上进行分析和翻译为翻译单元[...]

[...]Each preprocessing token is converted into a token. (2.7). The resulting tokens are syntactically and semantically analyzed and translated as a translation unit[...]

作为旁注,我们可以看到 Boost 包含一个特殊的宏来处理这种情况: BOOST_PP_COMMA:

As a side note we can see the Boost includes a special macro to deal with this situation: BOOST_PP_COMMA:

BOOST_PP_COMMA 宏扩展为逗号.

The BOOST_PP_COMMA macro expands to a comma.

并说:

预处理器将逗号解释为宏调用中的参数分隔符.因此,逗号需要特殊处理.

The preprocessor interprets commas as argument separators in macro invocations. Because of this, commas require special handling.

和一个例子:

BOOST_PP_IF(1, BOOST_PP_COMMA, BOOST_PP_EMPTY)() // expands to ,

这篇关于C++ assert:断言宏中表达式的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆