如果有一个if-constexpr,那为什么没有switch-constexpr? [英] If there's an if-constexpr, how come there's no switch-constexpr?

查看:63
本文介绍了如果有一个if-constexpr,那为什么没有switch-constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 17中, if constexpr 被介绍;但是,似乎没有 switch constexpr (请参见这里).这是为什么?也就是说,如果编译器支持 if constexpr ,那么支持 switch constexpr 也是一件很琐碎的事情(最糟糕的是,如果是if-then-else-if-etc.链或多个if(带有一些标志来控制失败率)?

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)?

推荐答案

if constexpr 最终源自更多理智的形式."rel =" noreferrer> 静态if 概念.因此,标准委员会似乎未考虑将相同的想法应用于 switch .因此,这可能是主要原因:没有人将其添加到论文中,因为这是一种受限形式的语法,其中 switch 毫无意义.

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 been considered by the standards committee. So this is likely the primary reason: nobody added it to the paper since it was a restricted form of a syntax where switch wouldn't have made sense.

话虽这么说, switch 里面有很多行李.最值得注意的是自动掉线行为.这使得定义它的行为有点麻烦.

That being said, switch has a lot of baggage in it. The most notable bit being the automatic fallthrough behavior. That makes defining its behavior a bit problematic.

请参见, if constexpr 的功能之一是在某些条件下丢弃在编译时未使用的那一侧.这是语法的重要部分.因此,假设假设的 switch constexpr 具有相似的功效.

See, one of the powers of if constexpr is to make the side not taken at compile time be discarded under certain conditions. This is an important part of the syntax. So a hypothetical switch constexpr would be expected to have similar powers.

这与失败测试要困难得多,因为 case 块与 if 语句的两个块在本质上不一样.特别是如果您有有条件的掉线.现在,您可以使 switch constexpr 不具有自动穿通(或完全不具有穿通),以便使不同的部分区分开.但是,然后您已经巧妙地更改了语法的工作方式. switch 的非 constexpr 形式的行为与 constexpr 形式不同.那不是很好.

That's a lot harder to do with fallthrough, since the case blocks are not as fundamentally distinct as the two blocks of an if statement. Especially if you have conditional fallthrough. Now, you could make switch constexpr not have automatic fallthrough (or fallthrough at all), so that the different sections are distinct. But then you've subtly changed how the syntax works; a non-constexpr form of switch behaves differently from the constexpr form. That's not good.

是的,如果不在标签之间放置 break; 语句,可能会导致编译错误.

Yes, you could make it a compile error to not put break; statements between the labels.

请注意,两个主要的模式匹配建议 P1308

Note that the two main pattern-matching proposals, P1308 and P1260, specifically avoid using switch, instead inventing a new keyword. They both have constexpr aspects to them, but they make it abundantly clear that they are not switch/case.

这篇关于如果有一个if-constexpr,那为什么没有switch-constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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