简体   繁体   English

为什么 ISO c++17 不允许在条件中使用结构化绑定声明?

[英]Why doesn't ISO c++17 permit a structured binding declaration in a condition?

Clang emits a warning if I use a structured binding declaration as a condition:如果我使用结构化绑定声明作为条件,Clang 会发出警告:

$ cat hello.cc
int main() {
  struct A { int i; operator bool() { return true; } };
  if (auto [i] = A{0}) {
    return i;
  }
  return -1;
}
$ clang++-10 -std=c++17 hello.cc
hello.cc:3:12: warning: ISO C++17 does not permit structured binding declaration in a condition [-Wbinding-in-condition]                                                                                                                                                                               
  if (auto [i] = A{0}) {                                                                                                                                                                                                                                                                               
           ^~~                                                                                                                                                                                                                                                                                         
1 warning generated.

I don't see this in dcl.struct.bind or stmt.select ;我在dcl.struct.bindstmt.select中没有看到这个; where would I see that this is forbidden?我在哪里可以看到这是被禁止的?

Furthermore: what is the rationale behind forbidding this?此外:禁止这样做的理由是什么?

The grammar for the if statement is if 语句的语法是

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

and as you can see condition is required while the init-statement is optional.如您所见, condition是必需的,而init-statement That means in if (auto [i] = A{0}) that auto [i] = A{0} is the condition, not the init-statment .这意味着在if (auto [i] = A{0})auto [i] = A{0}是条件,而不是init-statment condition is defined as condition定义为

condition:
    expression
    attribute-specifier-seq(opt) decl-specifier-seq declarator brace-or-equal-initializer

and that does not allow for a structured binding as the grammar for that is并且不允许结构化绑定,因为它的语法

attribute-specifier-seq(opt) decl-specifier-seq ref-qualifier(opt) [ identifier-list ] initializer ;

Good news is you can get what you want by adding a condition to your if statement like好消息是你可以通过在你的 if 语句中添加一个条件来得到你想要的,比如

if (auto [i] = A{0}; i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM