Solved

Templates

Posted on 2000-03-30
8
310 Views
Last Modified: 2010-04-02
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?
0
Comment
Question by:radek_s
  • 5
  • 3
8 Comments
 
LVL 22

Expert Comment

by:nietod
Comment Utility
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.
0
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
Comment Utility
opps that was menat to answer.

continues
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
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.
0
 
LVL 10

Expert Comment

by:RONSLOW
Comment Utility
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.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 22

Expert Comment

by:nietod
Comment Utility
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!
0
 
LVL 10

Expert Comment

by:RONSLOW
Comment Utility
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.

0
 
LVL 10

Expert Comment

by:RONSLOW
Comment Utility
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).
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
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.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now