Differences between Class and Function Templates

The name of a template class is a compound name consisting of the template name and the full template argument list enclosed in angle braces. Any references to a template class must use this complete name. For example:

template <class T, int range> class ex
{
      T a;
       int r;
      // ...
};
//...
ex<double,20> obj1;     // valid
ex<double> obj2;        // error
ex obj3;                // error

C++ requires this explicit naming convention to ensure that the appropriate class can be generated.

A template function, on the other hand, has the name of its function template and the particular function chosen to resolve a given template function call is determined by the type of the calling arguments. In the following example, the call min(a,b) is effectively a call to min(int a, int b), and the call min(af, bf) is effectively a call to min(float a, float b):

// This example illustrates a template function.

template<class T> T min(T a, T b)
{
      if (a < b)
            return a;
      else
            return b;
}
void main()
{
      int a = 0;
      int b = 2;
      float af = 3.1;
      float bf = 2.9;
      cout << "Here is the smaller int " << min(a,b) << endl;
      cout << "Here is the smaller float " << min(af, bf) << endl;
}


Class Templates


Function Templates