Why does the false branch of “if constexpr” get compiled?

强颜欢笑 提交于 2020-08-26 10:23:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/63469333/why-does-the-false-branch-of-if-constexpr-get-compiled

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