templates and generics

Apr 28, 2009 at 12:36pm
why is there a need for both templates and generics whe both them are almost the same. i know the differences and the constraints of generics but why need both of them if templates are good enough or is it that templates are kind of modified generics or something....
Apr 28, 2009 at 12:40pm
What are you talking about? Generics are templates.
The only difference is that generics are from C# and templates are from C++.
Apr 28, 2009 at 12:48pm
Templates are how generics is implemented. That is, you cannot implement generic programming without templates (well, not in C++).

Remember, a template is simply a cut-n-paste form for the compiler to use to create new functions. The replaceable parts, types and constants, are filled-in as needed. For example:
1
2
3
4
5
6
7
template <typename Comparable>
Comparable max3( Comparable a, Comparable b, Comparable c )
  {
  return (a > b)
    ? ((a > c) ? a : c)
    : ((b > c) ? b : c);
  }

Now, suppose you want to find the maximum of three floats:
float f = max3 <float> ( 2.0, 2.9, 1.8 );

Sure, and what about strings?
string s = max3( string( "first" ), string( "third" ), string( "second" ) );

The reason it works, of course, is that the compiler uses the template to create two functions: one that works on floats and one that works on strings.

Hope this helps.
Apr 28, 2009 at 12:50pm

well then how would you account for these differences:

Templates are instantiated at compile time while generics at run time.

Templates support non-type parameters, template parameters, and default parameter values. These are not supported by generics.

Last edited on Apr 28, 2009 at 12:52pm
Apr 28, 2009 at 2:33pm
Generics are a C# construct and templates are a C++ construct. While Generics are also available through the Microsoft C++/CLI, this is NOT native C++, but an extension to C++ via Microsoft's .NET framework.

The differences are simply a result of the specific design decisions that were made by the C++ Standard designers for Templates and the Microsoft designers for the .NET Generics.

Any confusion as to why there are two substantially similar, but not completely identical, constructs lies sqaurely on Microsoft's shoulders.
Topic archived. No new replies allowed.