What sets C++ Templates and .NET Generics apart?

written by Ryan Olshan on Tuesday, December 20 2005

C++ Templates and .NET Generics are not the same. There are many differences between them, but the biggest thing that sets them apart is that C++ Templates are instantiated at compile-time while Generics are instantiated at run-time.

Since C++ Templates are instantiated at compile-time, a copy of the code for each instance is generated, replacing the type placeholders with the actual data type. It is the equivalent of creating separate methods that handle several data types. In other words, declaring List<int>, List<int>, List<string>, and List<long> will cause the compiler to generate code for each declaration. Even though there are two Lists of integers, the compiler will still generate the code for both Lists. This seems repetitive, but pretty harmless on the surface. However, what if you have two assemblies where List<int> in Assembly1 is dependent on List<int> in Assembly2, but List<int> in Assembly2 is seen as a completely different type then List<int> in Assembly1? This presents a problem as it is like attempting to return a long or another data type other than an integer.

On the other hand, since Generics are instantiated at run-time, generic specializations are created on demand and share the underlying code whenever possible. This resolves the problem present in C++ Templates as mentioned above.

Kick this post on .NET Kicks

Similar Posts

  1. What's wrong with this generic type?
  2. Nullable Types
  3. Generic Sub Classes

Post a comment