What is the Java equivalent of C++’s templates?
I know that there is an interface called Template. Is that related?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Templates as in C++ do not exist in Java. The best approximation is generics.
One huge difference is that in C++ this is legal:
There is no equivalent construct in Java. The best that you can say is
where
Somethinghas a method calledadd.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
then the C++ compiler will compile a version of
sumforintand a version ofsumfordouble.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
And, as should be expected by this point, C++ style template metaprogramming is impossible with Java generics.