Solved

Templates in C++

Posted on 2000-04-20
7
310 Views
Last Modified: 2010-04-02
Can somebody explain Templates in C++.? Iam basically a C programmer.
I have done little bit of C++ programming also. But I never get to
know templates well. It would be great if somebody can explain.
0
Comment
Question by:meerak
  • 5
7 Comments
 
LVL 3

Expert Comment

by:TEFKASG
ID: 2736653
Templates allow you to define a generic function or class that can be used with many different variable types.  A class template must be instatiated with the type you want to use, and the type must have all operation, performed on it within the class, defined.  For example, if the template  does an assignment, the = operator must be defined for the template base type.  Template functions are instatiated just by calling the function,with the base datatype you need to use and operations used on the base datatype in the function must be defined.
0
 
LVL 3

Expert Comment

by:TEFKASG
ID: 2736666
An example for function templates:

Whenever you need several functions with the same body but different parameters, you can use templates by writing a single template function with a generic base datatype for the parameters.  The templates must be writen before the main function. If using seperate files for the template, all template code goes in a .h file, including the body of the function.  When using templates you must be careful because the compiler expands and inserts all the template code into your executable.  So template functions do not have the overhead of a normal function call, but can cause "code bloat.

                                   
# include<iostream.h>

                                   
template <class t>                                    
void swap(t&x,t&y)                                    
{                                    
t temp;
                                   
temp=x;
                                   
x=y;
                                   
y=temp;
                                   
}
 The operator = must be defined for any class/datatype you use this function with for it to work properly.
                                   
int main()
                                   
{
                                       
int x,y;
                                         
cout<<"enter the values of x,y";
                                         
cin>>x>>y;

                                         
swap(x,y);
                                         
cout<<"the swaped value"<<x<<y;
                                   
return 0;

                                   
}
0
 
LVL 3

Accepted Solution

by:
TEFKASG earned 100 total points
ID: 2736688
And now a class example:

Say you want to create an array class holding values of some (yet undefined) type.  Let's call the type "T".  You write:


                                       
template<class T>                                        
class Array                                      
{
                                       
public:
                                           
Array(); // constructor
                                           
~Array(); // destructor
                                           
bool insert(const T& elt);
                                       
private:
                                           
T* pItems; // a pointer to the items of type "T"
                                       
};

  Using class templates can cause code bloat as well.
                                   
That means: This is not really a class but a template that explains how the class should look like.  It is used to create a whole family of classes that look similar.  In order to create a class, the type
                                   
"T" has to be specified.

                                   
Now, say you want to provide an implementation of a member function.  You write:

                                       
template<class T>
                                       
bool Array<T>::insert(const T& elt)
                                       
{
                                            // Do something...
 
                                     
}

                                   
This is still a template.  The unspecified type(s) is/are: "T".  The member function belongs to the class family "Array" parametrized by "T" (for every T).

                                   
Say you want to create an implementation for the type "char" that will be different from the default implementations for all other types.  You write:

                                       
bool Array<char>::insert(const T& elt)
                                       
{
                                           
// Do something completly different...
                                       
}


                                   
 Now, say you want to use the template to create an array of "float" values.  You write:

                                       
int main()
                                       
{
                                           
float item = 1.0F;

                                           
Array<float> arr;
                                           
arr.insert(item);

                                           
return 0;
                                       
}
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 3

Expert Comment

by:TEFKASG
ID: 2736706
I think that should about cover it which is why I posted the last example as an answer.  Template classes are also wholly contained in a .h file.  For both function and class templates, I believe you can also use an inline file, but I have never done it that way.  Any questions?
0
 

Expert Comment

by:Yo081699
ID: 2737640
But no compiler handles complex templates correctly.

I'm not sure but I think that in his first example TEFKASG has actually defined an inline function template, implicitly, by writing the swap function definition without declaring it before.

I believe that the correct code for a normal function template would be :

template <class t>                                      
                    void swap(t&x,t&y);                                      


template <class t>                                      
        void swap(t&x,t&y)                                      
        {           t temp;
                     temp=x;
                     x=y;
                     y=temp;}
0
 
LVL 3

Expert Comment

by:TEFKASG
ID: 2738086
Yes, that would be right, for a complex function.  I tend to make most of my template functions inline. Which reminds me, only inline template functions don't have the overhead of a function call, but regular template functions, still do have the overhead of a function call.  Both types of template function still can contribute to "code Bloat," however.  
0
 
LVL 1

Author Comment

by:meerak
ID: 2753034
Thanks a lot
0

Featured Post

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!

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…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

744 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

13 Experts available now in Live!

Get 1:1 Help Now