Solved

Templates in C++

Posted on 2000-04-20
7
311 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
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 additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

895 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

15 Experts available now in Live!

Get 1:1 Help Now