I’m a beginning C++ programmer coming from Java.
It feels to me that C++ templates and Java generics are actually pretty similar. You use them in pretty much the same occasions and in the same way. And they ‘feel’ the same. However I can think of two differences between the systems:
-
In Java you can only use class-types as type arguments, while in C++ any type fits. I don’t think this is significant because Java autoboxing is good.
-
A more significant difference: C++ templates are duck typed. Meaning you can call any operation on a generic type
T
. If it doesn’t support the operation, a compile time error is raised. Java generics however aren’t duck typed. By default all type arguments are of typeObject
, and you can specify something more specific by the syntaxT extends Something
, which allows us to call onT
methods defined inSomething
.
The second point is rather significant. However apart from that, what are the differences between the two systems? What are the pros and cons of each one? Are they similar or different overall?
3
Implementation of the generics is night and day:
-
In java the compiled code removes all references to the generic type and adds casts where necessary. This is called type erasure and lets you do
List<String> list; ((List)list).add(new Object());
which will only throw an error when you try to get the value as a string. All java generics actually are is syntactic sugar with extra compile-time type checking. -
In C++ when you use a template the compiler will emit the template code again after replacing the generic parameter in it with the type you used. This is more powerful in several ways but can lead to bloated executables.
4