if-constexpr

Is “if constexpr” useful outside of templates?

时光怂恿深爱的人放手 提交于 2021-02-18 22:51:52
问题 I'm trying to understand if constexpr fully. I understand, that if if constexpr(expr) used in a template, and expr is dependent on a template parameter, then during instantiation, only one of the then / else branches will be instantiated, the other will be discarded. I've got two questions: Is it true, that if expr is not dependent on a template parameter, then no branches of if constexpr(expr) will be discarded? If yes, where does the standard say so? I don't see where the standard has the

If there's an if-constexpr, how come there's no switch-constexpr?

时光怂恿深爱的人放手 提交于 2021-02-18 11:17:04
问题 In C++17, if constexpr was introduced; however, there doesn't seem to be a switch constexpr (see here). Why is that? That is, if a compiler supports if constexpr , is it not also trivial for it to support switch constexpr (at worst as an if-then-else-if-etc. chain, or multiple if's with some flags to control fallthrough)? 回答1: if constexpr was ultimately derived from a more sane form of the static if concept. Because of that derivation, applying the same idea to switch does not appear to have

Wrong understanding of 'if constexpr'

不羁的心 提交于 2020-12-26 07:54:19
问题 I have following code static constexpr bool condition = true; int square(int num) { if constexpr (condition) { return num * num; } else { x return num; } } int main() { return square(3); } compiled with -std=gnu++17 My assumption for if constexpr (condition) was that during compilation the part } else { x return num; } get discarded and I get no error about the undefined x Is my understanding wrong that this 'if constexpr' is something like #ifdef CONDITION return num * num; #else x return

Wrong understanding of 'if constexpr'

与世无争的帅哥 提交于 2020-12-26 07:53:48
问题 I have following code static constexpr bool condition = true; int square(int num) { if constexpr (condition) { return num * num; } else { x return num; } } int main() { return square(3); } compiled with -std=gnu++17 My assumption for if constexpr (condition) was that during compilation the part } else { x return num; } get discarded and I get no error about the undefined x Is my understanding wrong that this 'if constexpr' is something like #ifdef CONDITION return num * num; #else x return