20

Possible Duplicate:
What are the differences between Generics in C# and Java… and Templates in C++?

What are the differences between C# generics compared to C++ templates? I understand that they do not solve exactly the same problem, so what are the pros and cons of both?

Community
  • 1
  • 1
Bjarke Freund-Hansen
  • 28,728
  • 25
  • 92
  • 135
  • 5
    What a coincidence, that is my blog topic for today. http://blogs.msdn.com/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx – Eric Lippert Jul 30 '09 at 18:12
  • 1
    this has *got* to be exact duplicate. @Eric Lippert: Ooh, interesting, will give it a read – jalf Jul 30 '09 at 21:39

5 Answers5

33

You can consider C++ templates to be an interpreted, functional programming language disguised as a generics system. If this doesn't scare you, it should :)

C# generics are very restricted; you can parameterize a class on a type or types, and use those types in methods. So, to take an example from MSDN, you could do:

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}

And now you can declare a Stack<int> or Stack<SomeObject> and it'll store objects of that type, safely (ie, no worried about putting SomeOtherObject in by mistake).

Internally, the .NET runtime will specialize it into variants for fundamental types like int, and a variant for object types. This allows the representation for Stack<byte> to be much smaller than that of Stack<SomeObject>, for example.

C++ templates allow a similar use:

template<typename T>
class Stack
{
    T *m_Items;
    public void Push(const T &item)
    {...}
    public T Pop()
    {...}
};

This looks similar at first glance, but there are a few important differences. First, instead of one variant for each fundamental type and one for all object types, there is one variant for each type it's instantiated against. That can be a lot of types!

The next major difference is (on most C++ compilers) it will be compiled in each translation unit it's used in. That can slow down compiles a lot.

Another interesting attribute to C++'s templates is they can by applied to things other than classes - and when they are, their arguments can be automatically detected. For example:

template<typename T>
T min(const T &a, const T &b) {
  return a > b ? b : a;
}

The type T will be automatically determined by the context the function is used in.

These attributes can be used to good ends, at the expense of your sanity. Because a C++ template is recompiled for each type it's used against, and the implementation of a template is always available to the compiler, C++ can do very aggressive inlining on templates. Add to that the automatic detection of template values in functions, and you can make anonymous pseudo-functions in C++, using boost::lambda. Thus, an expression like:

_1 + _2 + _3

Produces an object with a seriously scary type, which has an operator() which adds up its arguments.

There are plenty of other dark corners of the C++ template system - it's an extremely powerful tool, but can be painful to think about, and sometimes hard to use - particularly when it gives you a twenty-page long error message. The C# system is much simpler - less powerful, but easier to understand and harder to abuse.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • 2
    *Another interesting attribute to C++'s templates is they can by applied to things other than classes* - is this the same thing as C# allows us to define generics in functions (e.g. `T SomeFunc(T input){...}`) ? – dotNET Oct 06 '16 at 07:50
  • C++ Templates will execute faster because they are compiled in C++ to machine code (and maybe because they are compiler macros, instead of being overly generic). But C# objects don't have to be re-compiled can be placed into a dll. If you are developing a program that allows for dynamic code execution, it is possible to use a C# Generics object or function that is plugged in at runtime, with no recompile needed. I believe that this trick would be harder to pull off in C++, since its templated functions or things have to be compiled to get different instances of them. – John Foll Sep 16 '19 at 20:53
5

http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88913.aspx

Roughly, much of the difference has to do with the fact that templates are resolved at compile-time, and generics are resolved at runtime.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
  • 2
    Actually although generics can be instantiated at runtime (through reflection, just like anything else), a lot is figured out at compile time. For example, the JIT produces a specific implementation of `List` rather than using a common type-erased version equivalent to `List` (this is one way it differs from Java). – Daniel Earwicker Jul 30 '09 at 17:48
  • @Earwicker: tell me about it. That's why you can't do generic promotion (i.e. concatenating a List to a List). The functionality exists in the CLI, but they chose not to implement it that way in C# (a mistake, IMO). – Paul Sonier Jul 30 '09 at 18:21
2

Extensive answer on Stack Overflow: What are the differences between Generics in C# and Java... and Templates in C++?

Community
  • 1
  • 1
Richard Berg
  • 20,629
  • 2
  • 66
  • 86
1

This blog entry from Eric Gunnerson covers this topic quite well.

The biggest immediate difference is that templates are a compile time feature whereas generics are a runtime feature.

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
-1

This looks like a handy reference.

http://msdn.microsoft.com/en-us/library/c6cyy67b.aspx

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284