“一般”和“一般”之间的区别是什么,类型在C ++和Java? [英] What are the differences between "generic" types in C++ and Java?

查看:268
本文介绍了“一般”和“一般”之间的区别是什么,类型在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天全站免登陆