“通用"和“通用"之间有什么区别?C++ 和 Java 中的类型? [英] What are the differences between "generic" types in C++ and Java?

查看:42
本文介绍了“通用"和“通用"之间有什么区别?C++ 和 Java 中的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 具有泛型,而 C++ 提供了一个非常强大的带有 template 的编程模型.那么,C++ 和 Java 泛型有什么区别?

Java has generics and C++ provides a very strong programming model with templates. So then, what is the difference between C++ and Java generics?

推荐答案

它们之间有很大的不同.在 C++ 中,您不必为泛型类型指定类或接口.这就是您可以创建真正通用的函数和类的原因,但需要注意的是更宽松的类型.

There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing.

template <typename T> T sum(T a, T b) { return a + b; }

上面的方法添加了两个相同类型的对象,并且可以用于任何具有+"运算符可用的类型 T.

The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.

在 Java 中,如果要对传递的对象调用方法,则必须指定类型,例如:

In Java you have to specify a type if you want to call methods on the objects passed, something like:

<T extends Something> T sum(T a, T b) { return a.add ( b ); }

在 C++ 中,泛型函数/类只能在头文件中定义,因为编译器为不同的类型(调用它的)生成不同的函数.所以编译比较慢.在 Java 中,编译没有重大损失,但 Java 使用了一种称为擦除"的技术,其中泛型类型在运行时被擦除,因此在运行时 Java 实际上调用 ...

In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...

Something sum(Something a, Something b) { return a.add ( b ); }

因此,Java 中的泛型编程并不是真正有用,它只是帮助新的 foreach 构造的一点语法糖.

So generic programming in Java is not really useful, it's only a little syntactic sugar to help with the new foreach construct.

上面关于有用性的意见是由年轻的自己写的.Java 的泛型当然有助于类型安全.

the opinion above on usefulness was written by a younger self. Java's generics help with type-safety of course.

这篇关于“通用"和“通用"之间有什么区别?C++ 和 Java 中的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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