标准是否保证带有初始化的constexpr if?'constexpr(constexpr auto x = f(); x) { }'

6

我在http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0128r1.html中找不到有关C++17新的初始化语法和'constexpr if'的任何信息。

然而,这种语法得到了Clang-HEAD的支持...

constexpr auto f() { return true; }
int main() {
    if constexpr(constexpr auto x = f(); x) { }
}

在线代码 -> http://melpon.org/wandbox/permlink/dj3a9ChvjhlNc8nr

标准是否保证了带有初始化的constexpr if,因为constexpr if只是一个带有constexpr的"if",还是必须明确添加到标准中才能保证?


在 EWG 中有一次关于我们是否需要这个功能的讨论,其中提到使用两种特性可以极大地改善 Boost.Hana 风格的元编程(而不仅仅是使用 if constexpr),因此大家都同意采用它(几乎所有人都赞成,只有一票反对)。 - Griwes
1个回答

7
带初始化的选择语句提案提到了if constexpr,并且声明“该提案中扩展的if语句与if constexpr的功能一样好”。在N4606 [stmt.if]p3中,对于带初始化的if语句进行了规定,明确允许使用if constexpr。N4606 [stmt.if]p3的内容如下:

An if statement of the form

if constexpr[opt] ( init-statement condition ) statement

is equivalent to

{
  init-statement
  if constexpr[opt] ( condition ) statement
}

and an if statement of the form

if constexpr[opt] ( init-statement condition ) statement else statement

is equivalent to

{
  init-statement
  if constexpr[opt] ( condition ) statement else statement
}

except that names declared in the init-statement are in the same declarative region as those declared in the condition.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接