What does the void() in decltype(void()) mean exactly?

岁酱吖の 提交于 2019-11-26 20:33:54

问题


This is a follow-up of this question, more precisely of the comments of this answer.

What does the void() in decltype(void()) represent exactly?
Does it represent a function type, an expression or whatever?


回答1:


Using a hyperlinked C++ grammar, the parsing of decltype(void()) is:

decltype( expression )
decltype( assignment-expression )
decltype( conditional-expression )

... lots of steps involving order of operations go here ...

decltype( postfix-expression )
decltype( simple-type-specifier ( expression-listopt ) )
decltype( void() )

So void() is a kind of expression here, in particular a postfix-expression.

Specifically, quoting section 5.2.3 [expr.type.conf] paragraph 2 of the 2011 ISO C++ standard:

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, which is value-initialized (8.5; no initialization is done for the void() case).

So void() is an expression of type void, just as int() is an expression of type int (with value 0). Clearly a void expression has no value, but here it's the operand of decltype, so it's not evaluated. decltype refers only to its operand's type, not its value.

decltype(void()) is simply a verbose way of referring to the type void.




回答2:


I'm quoting the comment of @JoachimPileborg that seems to explain it correctly:

I think I figured it out now, decltype needs an expression, and not a type. void() is not actually a type here, but an expression, a C-style cast (just like e.g. int(12.34)) void(void) is not an expression therefore it doesn't work. How the compiler parses different things depends on the context, when it expects a type it parses as a type, when it expects an expression it parses as an expression. sizeof() (with the parentheses) expects first of all a type, otherwise it's parsed as a parenthesized expression.

I'm not looking for credits or reputation.
Anyway, I guess that was an interesting answer in the answer that is worth of a dedicated question for future readers.



来源:https://stackoverflow.com/questions/39279074/what-does-the-void-in-decltypevoid-mean-exactly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!