I have the knowledge of C++ template, but don’t know Java.
Would someone explain to me?
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.
They are actually implemented in very different ways. In C++, templates are specializated at compile time, while .Net generics are specialized at runtime.
In other words, C++ code like
MyClass<A> acauses the compiler to perform the template parameter substitutions and generate the binary for the class as if it was a regular class when it is compiled.Here’s what I mean:
This is compiled to something like this:
So templates “don’t exist” in the resulting binary of the compiled C++ code.
In .Net, the same line would cause the compiler to emit metadata for the class that indicates that the generic type parameters should be substituted in at runtime. It’s actually not as bad as it sounds, since the JIT compiler should be able to deal with them smartly.
This is compiled with extra information indicating that it’s a generic class. The
Tparameter is filled in at runtime when it is used:.Net generics do not attempt to replicate all of C++ template functionality. C++ templates are significantly more powerful at the expense of being significantly more difficult to work with (C++ templates are in fact Turing-complete).