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

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

问题描述

在C ++中:

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

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

任何人都可以解释为什么?

Can anyone explain why?

推荐答案

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

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:表达式在assert宏中的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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