Wednesday, June 24, 2009

C++ template and C# template

C++ template and C# template

In standard C++, template classes are resolved at compile time, basically "class generators" for the compiler. The compiler will generate a copy of the class definition for each type that is used for the template parameter. So, for "vector" and "vector", you'll end up with two seperate classes, one each for the types int and float.

In .NET 2.0+ (not just C#), generic classes are resolved at runtime. They are special constructs that maintain their type information. There is only ever one copy of the class definition, and that class definition keeps track of the type of objects being used with it. So, "List" and "List" use the same class definition.

Because of this, you can created a templated class of managed types because the runtime type information is unimportant to the template class, but you cannot create a generic class of unmanaged types, as the type information for unmanaged types isn't availabe at runtime.

No comments: