静态类型语言如何在没有泛型的情况下处理?
我很好奇哪些静态类型语言没有泛型支持 (以及在较小程度上哪些语言历史上没有泛型),以及它们如何处理它。
用户是否只是到处投射?对于基本集合(例如列表和字典)是否有一些特殊的调味料,可以使这些类型变得通用?
为什么这些语言没有泛型?是为了避免潜在的复杂性还是其他原因?
I'm curious which statically-typed languages have no generics support
(and to a lesser extent which languages historically did not have generics), and how they deal with it.
Do users just cast all over the place? Is there some special sauce for basic collections, like lists and dictionaries, that allow those types to be generic?
Why do these languages not have generics? Is it to avoid potential complexity or other reasons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对此问题的简短回答是 C++ 模板。与限制现有类型的泛型不同,模板是在编译时生成新类型的一种方式。与大多数代码生成解决方案一样,它并不是一个非常令人满意的解决方案:因此我们继续前进。
The short answer to this is C++ templates. Unlike generics, which restrict existing types, templates are a way of generating new types at compile time. Like most code-generating solutions, it's not a very satisfactory one: hence we have moved on.
Pascal 在其原始形式中不支持泛型。如果您想要一个链接列表,则需要为您的特定类型创建一个链接列表(例如 IntLinkedList)。
现代版本的 Pascal(例如 ObjectPascal/Delphi)可能提供某种形式的泛型。
Pascal, in its original forms, did not support generics. If you wanted a linked list, you needed to make one for your specific type (e.g. IntLinkedList).
Modern versions of Pascal (e.g. ObjectPascal/Delphi) may provide some form of generics.
C# 直到 v2.0 才支持泛型。所以是的,那么您需要从
Object
进行大量转换。我想 VB.Net 也是如此。
C# didn't support generics until v2.0. So yes, then you needed a lot of casting from
Object
.I guess the same goes for VB.Net.
C 以及历史上的 C++(在被称为 C++ 之前)要求您手动将“泛型”类型扩展为非泛型(即相当于 C++ 模板的 C 预处理器宏)或转义类型系统(即 void 指针)。
但是,数组(列表)被视为复合类型而不是单一类型。例如,您可以拥有一个短整型数组,但不能将其视为一个字符数组,甚至不能将其视为长整型数组。
这在 C 语言中并不是一个大问题,尽管有时会很不方便。从具体情况来看,它确实代表了 40 年前的一种权衡。
C—and historical C++, before it was called C++—requires you to either manually expand "generic" types into non-generics (i.e. the C preprocessor macro equivalent of C++ templates) or escape the type system (i.e. void pointers).
However, arrays (lists) are treated as composite types rather than a single type. You can have an array of shorts, for example, but you could not treat it the same as an array of chars or even of longs.
This isn't a really big problem in C, though inconvenient at times. It does represent a trade-off from 40 years ago, to put it in context.
下载 java 1.4 或 1.3 并亲自尝试一下。
提示:是的,可能会有很多强制转换
如何处理:我见过一个组织强制任何API不要使用集合(在方法声明中),而是使用数组来避免给用户带来困惑。另一种方法是创建一个仅适用于特定类的特定集合类,例如
StringList
等Download java 1.4 or 1.3 and try it yourself.
Hint: Yes there will be probably many casts
How to deal: I've seen an organization forcing any API not to use collection (in the method declaration) but array to avoid confusion to the user. Alternative is to create a specific collection classes that only works with certain class for example
StringList
etc