Solved

Templates in C++

Posted on 2000-04-20
7
315 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
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 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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Focus not getting shifted out of  editbox 2 69
thread-safe code in c++ 2 120
designing in object programming 12 104
C++ help/ Toy problem 19 50
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
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 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.
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.

763 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