Using generic methods?

c++, generics, java, programming-languages

Solution

Okay, Java generics and C++ templates are so different that I'm not sure it's possible to answer them in a single question.

Java Generics

These are there pretty much for syntactic sugar. They are implemented through a controversial decision called type erasure. All they really do is prevent you from having to cast a whole lot, which makes them safer to use. Performance is identical to making specialized classes, except in cases where you are using what would have been a raw data type (int, float, double, char, bool, short). In these cases, the value types must be boxed to their corresponding reference types (Integer, Float, Double, Char, Bool, Short), which has some overhead. Memory usage is identical, since the JRE is just performing the casting in the background (which is essentially free).

Java also has some nice type covariance and contravariance, which makes things look much cleaner than not using them.

C++ Templates

These actually generate different classes based on the input type. An `std::vector<int>` is a completely different class than an `std::vector<float>`. There is no support for covariance or contravariance, but there is support for passing non-types to templates, partial template specialization. They basically allow you to do whatever you want.

However, since C++ templates create different classes for every variation of their template parameters, the size of the compiled executable is larger. Beyond that, compilation time increases greatly, since all template code must be included with each compilation unit and much more code must be generated. However, actual runtime memory footprint is typically smaller than the alternative (frees an extra void*) and performance is better, since the compiler can perform more aggressive optimizations with the known type.

EDIT (thanks David Rodríguez): While a generic Java class compiles it's entire self, when using a C++ template, you only compile what you use. So, if you create an `std::vector<int>` and only use `push_back` and `size`, only those functions will be compiled into the object file. This eases the size of executable problem.

If you're curious about the differences between them, check out this comparison of generics in C#, Java and C++.

Problem

What are the benefits and disadvantages of using generic methods (in compile time, run time, performance, and memory)?

Original source