Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Templates in C++

Posted on 2000-04-20
7
Medium Priority
?
322 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 300 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
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 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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
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…
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 use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

916 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