C ++开关只用于整数类型的原理是什么? [英] What is the rationale for C++ switch only working for integral types?

查看:145
本文介绍了C ++开关只用于整数类型的原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得C ++应该允许 switch()超过可以比较的任何类型,而不只是整数类型。看起来很奇怪:

I feel that C++ should allow switch() over any type that can be compared, not just integral types. It seems odd that:

switch(myEnum)
{
    case myEnumValue1:
        ... break;
    case myEnumValue1:
        ... break;
}

在语义上与以下相同:

if(myEnum == myEnumValue1)
    ...
else if(myEnum == myEnumValue2)
    ...

但这只适用于整数类型。为什么?这种限制的目的是什么?

But this only works on integral types. Why? What is the purpose of such a restriction?

我知道编译器生成的代码 switch 只能与整体或寄存器大小类型兼容,但这些类型的东西通常是黑盒子从开发人员的决定。这些东西通常从我们这里抽象。如果跳转表更好,编译器应该生成一个。如果需要一个典型的 if / else 算法,那么。

I understand that the compiler-generated code for switch may only be compatible with integral or register-sized types, but these kinds of things are normally black-boxed from the developers' decisions. These kinds of things are normally abstracted from us. If a jump table is better, the compiler should generate one. If a typical if/else algorithm is needed, so be it.

推荐答案

switch语句继承自C,它本身设计在圣日,当效率仍然是一个问题。是的,这很可能是因为它允许计算gotos,即跳转表。

The switch statement was inherited from C, itself designed in the holy days when efficiency was still a concern. Yes, this is most probably because it allows "computed gotos", i.e. jump tables.

一系列的比较确实可以替代,但对于长的情况下,可能是优选的。不在此早期语言的范围。

A sequence of compares can indeed be an alternative, but for long case lists, hashing could be preferred. Not in the scope of this early language.

这篇关于C ++开关只用于整数类型的原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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