Thursday, December 01, 2005

How Are Generics Different from Classic Visual C++ Templates?

Generics are similar in concept to classic C++ templates: both allow data structures or utility classes to defer to the client the actual types to use, and both offer productivity and type-safety benefits.

There are two main differences: in the programming model and in the underlying implementation. In the programming model, .NET generics can provide enhanced safety compared to classic Visual C++ templates. .NET generics have the notion of constraints, which gives you added type safety. On the other hand, .NET generics offer a more restrictive programming model—there are quite a few things that generics cannot do, such as using operators, because there is no way to constraint a type parameter to support an operator. This is not the case in classic Visual C++ templates where you can apply any operator you like on the type parameters. At compile time, the classic Visual C++ compiler will replace all the type parameters in the template with your specified type, and any incompatibility is usually discovered then.

Both templates and generics can incur some code bloat, and both have mechanisms to limit that bloat. Instantiating a template with a specific set of types instantiates only the methods actually used; and then all methods that result in identical code are automatically merged by the compiler which prevents needless duplication. Instantiating a generic with a specific set of types instantiates all of its methods, but only once for all reference type arguments; bloat comes only from value types, because the CLR instantiates a generic separately once for each value type argument. Finally, .NET generics allow you to ship binaries, while C++ templates require you to share some code with the client.

Adopted from Generics FAQ: Fundamentals by Juval Lowy.


Post a Comment

<< Home