Open In App

Templates in C++ vs Generics in Java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

While building large-scale projects, we need the code to be compatible with any kind of data which is provided to it. That is the place where your written code stands above that of others. Here what we meant is to make the code you write be generic to any kind of data provided to the program regardless of its data type. This is where Generics in Java and the similar in C++ named Template come in handy. While both have similar functionalities, but they differ in a few places.

Template in C++

Writing Generic programs in C++ is called Templates.

  1. One of the major features of the template in C++ is the usage of metaprogramming. It Let the template signature of the provided code be different, were C++ provides the ability to implement them.
  2. Template arguments can be both classes and in functions.
  3. C++ requires template sources to be added in their headers.
  4. Template specialization could be achieved i.e, Specific type and method of template can be implemented.




// CPP program to illustrate Templates
#include <iostream>
#include <string.h>
  
using namespace std;
  
template <class T>
class TempClass {
  
    T value;
  
public:
    TempClass(T item)
    {
        value = item;
    }
  
    T getValue()
    {
        return value;
    }
};
  
int main()
{
    class TempClass<string>* String = 
      new TempClass<string>("Generics vs Templates");
  
    cout << "Output Values: " << String->getValue() 
         << "\n";
  
    class TempClass<int>* integer = new TempClass<int>(9);
    cout << "Output Values: " << integer->getValue();
}


Output:

Output Values: Generics vs Templates
Output Values: 9

Generics in Java

  1. One of the major features of Java Generics is that It handles type checking during instantiation and generates byte-code equivalent to non-generic code.
    The compiler of Java checks type before instantiation, that in turn makes the implementation of Generic type-safe. Meanwhile, in C++, templates know nothing about types.
  2. If Generics is applied in a class, then it gets Applied to classes and methods within classes.
  3. Another major factor that leads to the use of generics in Java is because it allows you to eliminate downcasts.
  4. Instantiating a generic class has no runtime overhead over using an equivalent class that uses as specific object rather than a generic type of T.




// Java program to illustrate
// Generics
public class GenericClass<T> {
private T value;
  
    public GenericClass(T value)
    {
        this.value = value;
    }
  
    public void showType()
    {
        System.out.println("Type:"
            value.getClass().getSimpleName());
        System.out.println("Value: " + value);
    }
  
    public static void main(String[] args)
    {
        GenericClass<String> Str = 
           new GenericClass<String>("Generics vs Templates");
  
        GenericClass<Integer> integer = 
                         new GenericClass<Integer>(9);
  
        Str.showType();
        integer.showType();
    }
}


Output:

Type:String
Value: Generics vs Templates
Type:Integer
Value: 9

C++ Templates vs Generics in Java

Though both of the methods to create a generic type is similar, but they vary at some places, while the implementation property that they possess is the same.

  1. Type erasure : Type erasure ensures tighter type check during compile time. Java generics simply offer compile-time safety and eliminate the need for casts. This is directly implemented in the Java compiler front-end and make sure type erasure is done.
  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.
  3. Wrapper class: In Java, Even if we have to specifically specify the datatype within which the function call using any object, we don’t need to cast it similar to that of C++ with actual data types, rather we use wrapper classes to do the required.
  4. Type Checking : Java Generics handles type checking during instantiation and generates byte-code equivalent to non-generic code C++ has “latent typing” and template metaprogramming and generates a new class for each instantiation

Java encourages software reuse and adds some basic support for generic programming. For Java, it is a serious step forward in the area of commercial software development.



Last Updated : 12 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads