Solved

Templates

Posted on 2000-03-30
8
313 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
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
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
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 learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

772 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