What are the differences between "generic" types in C++ and Java?

popopome picture popopome · Aug 30, 2008 · Viewed 95.4k times · Source

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

Answer

Alexandru Nedelcu picture Alexandru Nedelcu · Aug 30, 2008

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; }

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

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 ); }

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 ); }

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

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