为什么Java,C#和C ++没有范围? [英] Why don't Java, C# and C++ have ranges?

查看:52
本文介绍了为什么Java,C#和C ++没有范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ada

Ada, Pascal and many other languages support ranges, a way to subtype integers. A range is a signed integer value which ranges from a value (first) to another (last). It's easy to implement a class that does the same in OOP but I think that supporting the feature natively could let the compiler to do additional static checks.

我知道无法静态验证范围内定义的变量不会溢出"运行时(即由于输入错误),但我认为可以做些什么.我考虑了按合同设计方法(Eiffel)和规范#( C#合同),它提供了更为通用的解决方案.

I know that it's impossible to verify statically that a variabile defined in a range is not going to "overflow" runtime, i.e. due to bad input, but I think that something could be done. I think about the Design by Contract approach (Eiffel) and the Spec# ( C# Contracts ), that give a more general solution.

有没有更简单的解决方案,至少可以在C ++,C#和Java的编译时检查静态的带外分配?某种静态声明?

Is there a simpler solution that checks, at least, static out-of-bound assignment at compile time in C++, C# and Java? Some kind of static-assert?

修改:我知道范围"可以用于不同的目的:

edit: I understand that "ranges" can be used for different purpose:

  1. 迭代器
  2. 枚举器
  3. 整数子类型

我将重点讨论后者,因为前者很容易在C *语言上进行映射.我考虑了一组封闭的值,例如音乐音量,即从1到100的范围.我想将其增加或减少一个值.我想在静态溢出的情况下出现编译错误,例如:

I would focus on the latter, because the formers are easily mappable on C* language . I think about a closed set of values, something like the music volume, i.e. a range that goes from 1 up to 100. I would like to increment or decrement it by a value. I would like to have a compile error in case of static overflow, something like:

volume=rangeInt(0,100);
volume=101;  // compile error!
volume=getIntFromInput(); // possible runtime exception

谢谢.

推荐答案

在实践中,子范围类型实际上并不是很有用.我们不经常分配固定长度的数组,也没有理由要固定大小的整数.通常,在我们看到固定大小的数组的情况下,它们充当枚举,我们对此有一个更好的(尽管更重")解决方案.

Subrange types are not actually very useful in practice. We do not often allocate fixed length arrays, and there is also no reason for fixed sized integers. Usually where we do see fixed sized arrays they are acting as an enumeration, and we have a better (although "heavier") solution to that.

子范围类型也使类型系统复杂化.在变量之间引入约束比固定常量要有用得多.

Subrange types also complicate the type system. It would be much more useful to bring in constraints between variables than to fixed constants.

(必须提到整数在任何明智的语言中都应为任意大小.)

(Obligatory mention that integers should be arbitrary size in any sensible language.)

这篇关于为什么Java,C#和C ++没有范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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