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 type
Object, and you can specify something more specific by the syntax
T extends Something, which allows us to call on
Tmethods defined in
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?