• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

Templates in C++

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
meerak
Asked:
meerak
  • 5
1 Solution
 
TEFKASGCommented:
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
 
TEFKASGCommented:
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
 
TEFKASGCommented:
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
TEFKASGCommented:
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
 
Yo081699Commented:
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
 
TEFKASGCommented:
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
 
meerakAuthor Commented:
Thanks a lot
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now