Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of C++'s templates?

Tags:

What is the Java equivalent of C++'s templates?

I know that there is an interface called Template. Is that related?

like image 653
giri Avatar asked Jan 29 '10 01:01

giri


People also ask

What are templates in Java?

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function.

Are C++ templates and Java generics the same?

Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime.

What is class write class template in Java?

A class is a template for creating a particular form of object. A Java class definition corresponds to a C++ struct definition generalized to include all of procedures that process objects of the defined class. In Java, all program code must be part of some class.

Are C++ templates just generics?

Both generics and templates allow the same source code to be used with different types. The main difference is with what the source code is compiled to. In short: Generics = same bytecode code for all types (that meet the constraints); Templates = different machine code for each type actually used.


1 Answers

Templates as in C++ do not exist in Java. The best approximation is generics.

One huge difference is that in C++ this is legal:

<typename T> T sum(T a, T b) { return a + b; }  

There is no equivalent construct in Java. The best that you can say is

<T extends Something> T Sum(T a, T b) { return a.add(b); } 

where Something has a method called add.

In C++, what happens is that the compiler creates a compiled version of the template for all instances of the template used in code. Thus if we have

int intResult = sum(5, 4); double doubleResult = sum(5.0, 4.0); 

then the C++ compiler will compile a version of sum for int and a version of sum for double.

In Java, there is the concept of erasure. What happens is that the compiler removes all references to the generic type parameters. The compiler creates only one compiled version of the code regardless of how many times it is used with different type parameters.

Other differences

  • C++ does not allow bounding of type parameters whereas Java does
  • C++ allows type parameters to be primitives whereas Java does not
  • C++ allows templates type parameters to have defaults where Java does not
  • C++ allows template specialization whereas Java does not And, as should be expected by this point, C++ style template metaprogramming is impossible with Java generics.
  • Forget about seeing the curiously recurring template pattern in Java
  • Policy-based design is impossible in Java
like image 81
jason Avatar answered Oct 14 '22 20:10

jason