Click here to Skip to main content
15,886,806 members
Articles / Desktop Programming / ATL
Article

Template based programming

Rate me:
Please Sign up or sign in to vote.
2.27/5 (10 votes)
24 Mar 20022 min read 144.9K   46   20
As we already know of inheritance, it is a good way of reusing your code. However, Visual C++ provides another way of reusing your code. We can do this through templates. With templates you can make the 'type' parameter. Let me explain.

Introduction

As we already know of inheritance, it is a good way of reusing your code. However, Visual C++ provides another way of reusing your code. We can do this through templates. With templates you can make the 'type' parameter. Let me explain. When you had this class that shows all processor information. The class is huge, and it uses all integers. What if, in time, the integer wouldn't be able to store the information of the processor (just because it's out of range for the integer). Now you'll need to review all your code and change the integers to longs. Or when you have this class that handles int arrays, and someday you'll need the exact same class, only you want it to handle floats.

Details

For these problems we have templates. Let me show you some code:

class CMyIntArray
{ 
public: 
    int GetSize();//gets the size of the array int 
    SetSize();//sets the size of the array 
    void Add(int Value);//adds a value to the array etc...
}

As it becomes clear from this code, you cannot handle floats with this class. A float class would look like this:

class CMyFloatArray
{ 
public: 
    int GetSize();//gets the size of the array int 
    SetSize();//sets the size of the array 
    void Add(float Value);//adds a value to the array etc...
}

Ok, we can handle this little bit of change.. but what if you had lots of functions, and what if we needed them same class for short, char etc...

You might now the old C macros (#define), template based programming is just like that (in a way). But, type macros aren't type safe, templates are. If you want to know how to create a template please look at the code below:

//Use of templates in Visual C++ by Clemens Timmermans (maxcode.com)
template <typename Type>
class CMyArray
{ 
public:
    void Add(Type Value);
    int GetSize();
    int SetSize();
};

That wasn't so hard? right? Now lets see how we can USE this template, by the following code snippet:

...
// USING CMyArray
CMyArray <int> iArray;
iArray.Add(100);
////////////////////
CMyArray<float> fArray;
fArray.Add(10.2);
/////////////////////
...
//you got the point of basic template use!

No, finally, we may also use the Templates as containers. Checkout the following code:

class CMercedes
{
public:
    int GetMaxSpeed();//this gets the max speed of the car
    void SpeedUp();
    CMercedes();
    virtual ~CMercedes();
}

in template based programming we would make it look like this, no matter what the brand is.

//what if we want to create a template class 
//which needs to take any valid car

template <typename MyCar>
class CTemplateCar
{
private:
    MyCar theCar;
public:
    CTemplateCar(){}
    virtual ~CTemplateCar(){}
    void SpeedUpWhateverCarWeLike()
    {
        theCar.SpeedUp();
    }
}

now, as we want to use the template.. use this code to use it!

...
CTemplateCar<CMercedes>  car;
car.SpeedUpWhateverCarWeLike();
CTemplateCar<CFerrari>  car2;
car2.SpeedUpWhateverCarWeLike();
...

I hope this article has helped you understand the meaning of template based programming, but above all, how to use it and why use it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
zxw196217-Aug-10 16:53
zxw196217-Aug-10 16:53 
GeneralA couple of other points Pin
Christian Graus25-Mar-02 23:23
protectorChristian Graus25-Mar-02 23:23 
GeneralRe: A couple of other points Pin
Jörgen Sigvardsson26-Mar-02 1:14
Jörgen Sigvardsson26-Mar-02 1:14 
Christian Graus wrote:
Secondly, your container classes have no variables. The variables are kind of the point of template based programming, don't you think ?

Let's not forget types. binary_function for instance doesn't define any data, only types. I agree that it is not a container, but it is template based programming.

I really dig the type magic you can do with templates. A really cool thing is std::allocator<T1>::rebind<T2>::other. Imagine a "normal" container, i.e. a std::list<t>. It knows how to allocate chunks of memory for T since it is specified as a template argument. But how do you allocate the actual list nodes (which contain next and prev pointers)? Thats where the rebind<T>::other comes in to play.

template<class U>
struct rebind {
    typedef allocator<U> other;
};


So when the STL implementation of list allocates a node, it does something like this:
template <typename T, typename A = allocator<T> >
struct list
{
    // ...
    struct node
    {
        T d;
        node* prev;
        node* next;
    };

    typedef A::rebind<node>::other   A_node;
    A_node  node_alloc;

    void push_back(const T& t)
    {
        // ...
        node* new_node = node_alloc.allocate(1, NULL);
        // ...
    }

    // ...
};


Voila! The user of the list cannot specify an allocator of nodes, since the user should not be aware of its existance - it's an implementation detail of list. The list however must know how to allocate memory using the users allocation specifications, but it cannot do that "straight out of the box" - it was only given an allocator for T which is the user type to be contained in each node. The solution is simple and elegant: a pseudo recursive template called rebind.

The more I read and write template code, the more I fall in love with it. When's .NET going to support template code generation so that I can also fully enjoy it? Smile | :)

Sonorked as well: 100.13197 jorgen
FreeBSD is sexy.
GeneralRe: A couple of other points Pin
Christian Graus26-Mar-02 8:07
protectorChristian Graus26-Mar-02 8:07 
GeneralA couple of other points Pin
Christian Graus25-Mar-02 23:23
protectorChristian Graus25-Mar-02 23:23 
GeneralRe: A couple of other points Pin
Paul Selormey26-Mar-02 1:11
Paul Selormey26-Mar-02 1:11 
GeneralRe: A couple of other points Pin
Christian Graus26-Mar-02 8:05
protectorChristian Graus26-Mar-02 8:05 
GeneralRe: A couple of other points Pin
Paul Selormey26-Mar-02 13:23
Paul Selormey26-Mar-02 13:23 
GeneralRe: A couple of other points Pin
Christian Graus26-Mar-02 20:29
protectorChristian Graus26-Mar-02 20:29 
GeneralRe: A couple of other points Pin
Mike_Beard6-Aug-02 5:51
Mike_Beard6-Aug-02 5:51 
Generalrating math Pin
Nish Nishant25-Mar-02 14:20
sitebuilderNish Nishant25-Mar-02 14:20 
GeneralRe: rating math Pin
Christian Graus25-Mar-02 23:11
protectorChristian Graus25-Mar-02 23:11 
GeneralRe: rating math Pin
Nish Nishant25-Mar-02 23:20
sitebuilderNish Nishant25-Mar-02 23:20 
GeneralI'm sorry, but.... Pin
Christian Graus25-Mar-02 10:57
protectorChristian Graus25-Mar-02 10:57 
GeneralRe: I'm sorry, but.... Pin
Nish Nishant25-Mar-02 14:23
sitebuilderNish Nishant25-Mar-02 14:23 
GeneralRe: I'm sorry, but.... Pin
Christian Graus25-Mar-02 19:54
protectorChristian Graus25-Mar-02 19:54 
Generalhey Pin
Nish Nishant25-Mar-02 8:19
sitebuilderNish Nishant25-Mar-02 8:19 
GeneralThe game for baby Pin
soptest25-Mar-02 10:10
soptest25-Mar-02 10:10 
GeneralRe: The game for baby Pin
Nish Nishant25-Mar-02 14:24
sitebuilderNish Nishant25-Mar-02 14:24 
GeneralRe: The game for baby Pin
soptest25-Mar-02 14:37
soptest25-Mar-02 14:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.