Templates in C++ vs Generics in Java

12 Oct, 2021
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.
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.Template arguments can be both classes and in functions.C++ requires template sources to be added in their headers.Template specialization could be achieved i.e, Specific type and method of template can be implemented.
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.
Template arguments can be both classes and in functions.
C++ requires template sources to be added in their headers.
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 Values: Generics vs Templates
Output Values: 9

Generics in Java
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.If Generics is applied in a class, then it gets Applied to classes and methods within classes.Another major factor that leads to the use of generics in Java is because it allows you to eliminate downcasts.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.
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.
If Generics is applied in a class, then it gets Applied to classes and methods within classes.
Another major factor that leads to the use of generics in Java is because it allows you to eliminate downcasts.
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// Genericspublic 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();    }}
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.
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.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.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.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
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.
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.
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.
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.
This article is contributed by Aniketh Girish. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or email your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
thundercode
Akanksha_Rai
vaibhavsinghtanwar
C++
Java
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.