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

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

问题描述

Ada Pascal 和许多其他语言支持范围,一种子类型整数的方式。
范围是有符号整数值,范围从一个值(第一个)到另一个(最后一个)。
很容易实现一个在OOP中执行相同操作的类,但我认为支持该特性本身可以让编译器执行额外的静态检查。

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.

I知道不可能静态地验证一个范围中定义的变量不会溢出运行时,即由于错误的输入,但我认为可以做一些事情。
我认为按合同设计方法(Eiffel)和规范#(< a href =http://research.microsoft.com/en-us/projects/contracts/ =nofollow> C#Contracts ),它们提供了更通用的解决方案。

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天全站免登陆