Link to home
Start Free TrialLog in
Avatar of radek_s
radek_s

asked on

Templates

What are the "templates" in c++?
I read it's usefull to create
array of not fixed lenght.
Is it true?
So how to create this not_fixed_lenght
array?
Avatar of nietod
nietod

templates are use to create different classes or functions that are very similar but vary in specific ways.  The classic example is a minimize function.  if you write a function like

int min(int x,int y)
{
   return x<y?x:y;
}

and find you need to get the minimuim of a double, you have to write another function.  If you have to get the minimum of a class complex, you have to write a 3rd funtion and  4th and so on.  Instead you can write it as a template function where the data type (int in this case) is a template parameter and will be replaced by the needed data types.  like

template <class T>
T min(T x, T y)
{
   return x<y?x:y;
};

continues.
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As you can see in the example, the tempalte defines a template parameter called T that is the data type that is passed to and returned from the min() function.  Now the compiler can "write" min() functions for any data type.  it just follows the template you wrote and replaces all the T's with the data type needed, so now you can do

double D1, D2, D3;

 D3 = min(D1,D2);

and the compiler will write a version of min() that woks with double.

>> So how to create this not_fixed_lenght
You just write an typical array class, but use a template to insure that the data type stored can be changed (it is a template parameter) so that the array class can be used to store different types of data.   A full explanation of this is well beyond the cope of this question, but can be found in many modern C++ texts.    A short example to get you started might be

template <class T>
{
   class Array
    {
       T* DataPtr; // -> data.
       int Siz;
   public:
       Array(int IniSiz) : Siz(0),DataPtr(NULL) { SetSize(IniSiz); };
      ~Array()  {  delete [] DataPtr; };
      void SetSize(int S)
      {
          delete [] DatPtr;  
          DatPtr = new T[S];
          Siz= S;
      };
    };
}

obviously this is an incomplete class and is feature poor, but you can get an idea of how it works.  it can then be used to create array classes that store its, doubles, or other classes,  It could even store instances of other array classes!.

The STL class vector is a template array class.  You may want to examine it.
templates are a bit like macros .. but nicer.

eg. you can write a macro to give you the max of two values like this...

#define Max(X,Y) ((X>Y)?X:Y)

The problems with this are
1) no type checking
2) if an expression is used for either parameter, it is evaluated twice, this can be a problem is the expression is self-modifying (eg. has a ++ in it)
3) only single expressions (or several separated by commas) can be used easily
4) if you declare variables, you have to make sure that the names don't clash with those defined where the macro is used.

compare this with the template version

template <typename T> inline Max (T x, T y) { return x > y ? x : y; }

this checks that the tow args are of the same type, and doesn't have problems with names or arguments.

one way to get an array, btw is

template < typename T, int N > class Array {
  T array[n];
  ...
};

you get a unique class for each combination of type and array size.
That is all true and there are other benefits as well, they obey scope correctly--including namspaces scope, they may yield shorter programs, and more.    For the most part, there is no place in C++ for the pre-processor macros!
Well .. almost no place.

They do come in handy for partial code blocks.  And the token pasting and stringizing can do some neat tricks.

Certainly C++ gets rid of most uses for #define macros.. C++ has constants, inline functions and templates. Such direct language support for these things is better and safer than what #define can give you .. mostly because the compiler has extra information availalbe to it.

BTW: I prefer the syntax

  template <typename T> ...

to

  templae <class T> ...

unless the template parameter is always going to be an actual class (rather than some other type).
I find neat tricks end up being not-so-neat.  They may come back to haint you....

But then again I cheat.  I wrote a pre-processor of my own that does some "fixes" to the code.  I probably would have to use the standard pre-processor more if I didn't have that.