Ich habe Kenntnisse über C++-Vorlagen, aber kenne kein Java.
Könnte mir das jemand erklären?
Ich habe Kenntnisse über C++-Vorlagen, aber kenne kein Java.
Könnte mir das jemand erklären?
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
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
class MyClass
{
public:
void Foobar(const T& a);
};
int main()
{
MyClass 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
{
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 myclass = new MyClass();
.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).
Eine Möglichkeit, es zu betrachten, ist, dass die Vorlagenerweiterung zur Kompilierzeit erfolgt, aber Generics sind ein Feature zur Laufzeit in .Net.
Die C#-FAQ hat einen guten Artikel und einen Interview-Link, der einige der Unterschiede erläutert.
CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.