I have the knowledge of C++ template, but don't know Java.
Would someone explain to me?
I have the knowledge of C++ template, but don't know Java.
Would someone explain to me?
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> a
causes 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:
template<typename T>
class MyClass
{
public:
void Foobar(const T& a);
};
int main()
{
MyClass<int> myclass;
return 0;
}
This is compiled to something like this:
class MyClass_int // hypothetical class generated by compiler
{
public:
void Foobar(const int& a);
};
int main()
{
MyClass_int myclass;
return 0;
}
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.
public class MyClass<T>
{
public void Foobar(T item) {}
}
This is compiled with extra information indicating that it's a generic class. The T
parameter is filled in at runtime when it is used:
// This specialization occurs at runtime
MyClass<int> myclass = new MyClass<int>();
.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).
One way to look at it is that template expansion happens at compile time, but generics are a run time feature in .Net.
The C# faq has a good article and interview link that goes over some of the differences.