Solved

Templates

Posted on 2000-03-30
8
316 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 22

Expert Comment

by:nietod
ID: 2671163
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
ID: 2671167
opps that was menat to answer.

continues
0
 
LVL 22

Expert Comment

by:nietod
ID: 2671196
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:RONSLOW
ID: 2672801
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
 
LVL 22

Expert Comment

by:nietod
ID: 2672852
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
ID: 2672871
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
ID: 2672878
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
ID: 2672977
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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
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 viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

707 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