Difference between templates in C++ and generics in Java

Explain the difference between templates in C++ and generics in Java.

Solution:

  1. In C++ templates, parameters can be any type or integral but in Java, parameters can only be reference types (not primitive types).
    std::map<int, int> mapping;
    
    Map<Integer, Integer> mapping;
    
  2. For C++ templates, Separate copies of the class or function are likely to be generated for each type parameter when compiled. However for Java generics, only one version of the class or function is compiled and it works for all type parameters.
  3. For C++ templates, Implementation source code of the template class or function must be included in order to use it (declaration sufficient). For Java templates, Signature of the class or function from a compiled class file is sufficient to use it.
  4. C++ templates can be specialized – a separate implementation could be provided for a particular template parameter. In Java, generics cannot be specialized.
  5. C++ does not support wildcard. Instead, return types are often available as nested typedefs. Java supports wildcard as type parameter if it is only used once. The following Java code is valid:
    void printCollection(Collection<?> c) {
        for (Object e : c) {
            System.out.println(e);
        }
    }
    
  6. In C++, static variables are not shared between classes of different type parameters. In Java, static variables are shared between instances of a classes of different type parameters.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: