Reputation: 3563
I have repeatedly heard that generics in C# are less powerful than templates in C++. But I have not heard any arguments in favor of (or against) this. Is it really so, if so, in what it shows?
I recently faced with the strange feature that if SomeClassChild
is descendant of class SomeClass
, then List<SomeClassChild>
can not be converted to List<SomeClass>
, whereas SomeClassChild[]
to SomeClass[]
- can.
The following code will also result in an error:
List<SomeClass> lst = new List<SomeClass>();
lst.Add(new SomeClassChild());
Upvotes: 2
Views: 3561
Reputation: 6050
The book "C# in depth", it has a topic on comparing generics between languages. As C++/C#, I just copy some content form the book:
The C++ compiler is smart enough to compile the code only once for any given set of template arguments, but it isn’t able to share code in the way that the CLR does with reference types. That lack of sharing does have its benefits, though—it allows type specific optimizations, such as inlining method calls for some type parameters but not others, from the same template. It also means that overload resolution can be performed separately for each set of type parameters, rather than just once based solely on the limited knowledge the C# compiler has due to any constraints present.
One significant feature that C++ templates have over C# generics is that the template arguments don’t have to be type names. Variable names, function names, and constant expressions can be used as well. A common example of this is a buffer type that has the size of the buffer as one of the template arguments—a buffer will always be a buffer of 20 integers, and a bufferwill always be a buffer of 35 doubles. This ability is crucial to template metaprogramming (see the Wikipedia article, http://en.wikipedia.org/wiki/Template_metaprogramming), which is an advanced C++ technique, the very idea of which scares me but that can be powerful in the hands of experts.
C++ templates are more flexible in other ways too. They don’t suffer from the lack of operator constraints and there are a few other restrictions that don’t exist in C++: you can derive a class from one of its type parameters, and you can specialize a template for a particular set of type arguments. The latter ability allows the template author to write general code to be used when there’s no more knowledge available, and specific (often highly optimized) code for particular types.
If you want to find out more, check the book.
Upvotes: 4