c++ - void{} 是否合法?

标签 c++ language-lawyer void c++17 return-type-deduction

这是 this 的后续行动问题。
在评论和答案中,不止一次提到 void{} 既不是有效的类型 ID,也不是有效的表达式

这很好,很有意义,仅此而已。

然后我通过 [7.1.7.4.1/2] (占位符类型扣除)工作草案。
据说:

[...]
- for a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type and e is the operand of the return statement. If the return statement has no operand, then e is void{};
[...]

那么,void{}(在概念上)是否合法?
如果工作草案中提到它是可以接受的(即使只是作为一个 - 就好像它是一个 - 声明),它必须确实是合法的。这意味着 decltype(void{}) 也应该是有效的,例如。
否则,工作草案是否应该使用 void() 而不是 void{}


好吧,老实说,我很确定我不够熟练,无法指出工作草案中的错误,所以真正的问题是:我的推理出了什么问题?
上面项目符号中提到的 void{} 究竟是什么?为什么在这种情况下它是合法的表达方式?

最佳答案

对我来说,这听起来像是有人将旧标准与新标准合并在一起时搞砸了。

以前的标准是这样说的:(C++14 N4140, 7.1.6.4.7 [dcl.spec.auto]):

When a [...] return statement occurs in a function declared with a return type that contains a placeholder type, the deduced return type or variable type is determined from the type of its initializer. In the case of a return with no operand, the initializer is considered to be void().

较新的标准允许 if constexpr 语句,因此需要更改语言以反射(reflect)这一点。 if constexpr 导致了一个潜在的discarded return 语句的概念(如果 return 在 not-taken constexpr if 的分支,则将其丢弃,并从其他返回语句推断返回类型(如果有)。

可能新的措辞应该是这样的:

for a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type and e is the operand of the return statement. If the return statement has no operand, then T is auto and the deduced return type is void

关于c++ - void{} 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354065/

相关文章:

c++ - 将未使用的类数据成员存储在磁盘上

c++ - 通过模板访问标准容器的迭代器

C++ 嵌套类/前向声明问题

c++ - 空的大小是多少?

C++ void 类型 - 怎么样?

c - 警告 : return makes pointer from integer without a cast but returns integer as desired

C++动态分配内存

Ruby:为什么 'while (p || (p=exns.shift))' 与 'while p ||= exns.shift' 不同?

c++ - 将 C++ 对象传递给它自己的构造函数是否合法?

c - 这段c语言代码有什么问题?