?
Solved

Templates

Posted on 2000-03-30
8
Medium Priority
?
319 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 400 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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 how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

762 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