Thinking about Programming in C++

In 'The C++ Programming Language', Stroustrup states that:
"Another form of commonality can be expressed through templates (§2.7, Chapter 13). A class
template specifies a family of classes. For example, a list template specifies ‘‘list of T,’’ where
‘‘T’’ can be any type. Thus, a template is a mechanism for specifying how one type is generated
given another type as an argument. The most common templates are container classes such as lists,
arrays, and associative arrays and the fundamental algorithms using such containers. It is usually a
mistake to express parameterization of a class and its associated functions with a type using inheritance.
It is best done using templates.
"

I really can't understand the last sentence... What does it mean "parameterization of a class" ? It would be great if someone clears that.
Thanks.
For example, when instead of making a class List templated so that the type that its nodes hold can be defined by the user, you make it a safely derivable class that the user will have to inherit from. However there are a few, rare cases where this is what you need to do. For example:
1
2
3
4
5
6
7
8
9
10
BaseList *list;
switch (user_input()){
    case INTEGER:
        list=new IntegerList;
        break;
    case STRING:
        list=new StringList;
        break;
    //...
}
You can't do this with templates because they rely on compile time information, and input is run time information.
Last edited on
It means that something like this:

1
2
3
4
5
6
7
8
template <class T>
class Stack
{
    void push(T t);
    T pop();

    //...
};

is better than something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Stack
{
    virtual void push(void*);
    virtual void * pop();
};

class IntStack:public Stack
{
    void push(void*);
    void * pop();

    //...
};

class StrStack:public Stack
{
    void push(void*);
    void * pop();

    //...
}

//... 

Admittedly, I used to do it the wrong way -> http://cplusplus.com/forum/general/24971/#msg132485
But not any more -> http://cplusplus.com/forum/general/26119/#msg139250

EDIT:

helios wrote:
You can't do this with templates because they rely on compile time information, and input is run time information.

You can, if you have a non-templated base class and a templated derived class. Of course you have to use polymorpshism too, but you don't have to write a derived class for every type.
Last edited on
Topic archived. No new replies allowed.