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:

  1. 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.

  2. 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 T methods defined in Something.

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?

closed as too broad by gnat, user22815, GlenH7, user40980, BЈовић Oct 10 '14 at 6:17

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


Implementation of the generics is night and day:

  1. 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.

  2. 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.

  • 2
    So type erasure means: 'replace all the generic type references with references to Object, and add casts down to the generic type everywhere'? – Aviv Cohn Oct 9 '14 at 10:39
  • @AvivCohn just about – ratchet freak Oct 9 '14 at 10:40
  • As opposed to C++ templates (or C# generics, I think) which means that for every 'instantiation' of the class/function with a different generic parameter, an actual new instance of the function/class is put into the executable, using the appropriate type? – Aviv Cohn Oct 9 '14 at 10:45
  • @AvivCohn C++ templates will function this way, but C# generics do not. C# generics keep the type, but utilize the type at runtime instead of creating multiple methods like C++ does. – Peter Smith Dec 31 '14 at 16:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.