为什么“ if constexpr”的错误分支会出现?得到编译? [英] Why does the false branch of "if constexpr" get compiled?

查看:67
本文介绍了为什么“ if constexpr”的错误分支会出现?得到编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码在编译时出现错误?我的 <$ c知识(以及 this ) $ c> if constexpr 表示不应编译 else 块。

  if constexpr(true){
int a = 10;
} else {
int b = 10
}

错误为:

 错误:预期','或';'在'}'令牌

使用的编译器: g ++版本7.5.0

编译时我使用的是 -std = c + +17 标志。


PS 丢失的';'是故意的,只是为了检查 else 是否正在编译。

解决方案

这里有2个单独的但相关的问题


首先,如果constexpr 只会有条件地编译模板中的分支。


其次,即使在模板中, if constexpr 都不会格式错误。在您的代码中情况并非如此,因为:

  int b = 10 

总是格式错误(由于缺少; )。


所以编译器给出编译错误是正确的。从技术上讲,如果所有实例的废弃分支格式都不正确,则不需要要求给出编译器错误,但是代码仍然错误。


Why is this code giving error while compiling? My knowledge (and also this) of "if constexpr" says the else block shouldn't get compiled.

if constexpr (true) {
    int a = 10;
} else {
    int b = 10
}

The error is:

error: expected ‘,’ or ‘;’ before ‘}’ token

Compiler used: g++ version 7.5.0
While compiling I used -std=c++17 flag.

P.S. The missing ';' is intentional, just to check whether else is being compiled or not.

解决方案

There are 2 separate, but related issues here.

Firstly, if constexpr will only conditionally compile a branch within a template. Outside of a template, all branches will be compiled and must be well formed.

Secondly, even in a template, the discarded branch of an if constexpr can't be ill-formed for all possible instantiations. This is not the case in your code, since:

int b = 10

is always ill-formed (due to the missing ;).

So the compiler is correct in giving a compile error. Technically, if the discarded branch is ill-formed for all instantiations, then the compiler is not required to give a compiler error, but the code is still wrong.

这篇关于为什么“ if constexpr”的错误分支会出现?得到编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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