Instantiating a class template on the heap

Stroustrup writes that "If explicit use of the heap is undesirable, templates have an advantage over class hierarchies." ["The C++ Programming Language", 4th Ed, Ch 27 (Templates and Hierarchies), pg 762]

To substantiate this point, he gives the following example of a class template, and one of its specializations (elaborated slightly by me):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class A
{
};

class B
{
};


/// interface expressed in terms of the parameter
template<typename X>
class Ct        /// class template
{
    X mem;

public:
    X f()
    {
        return X {};
    }

    int g()
    {
        return int {};
    }

    void h(X)
    {
    }
};


/// specialization for A
template<>
class Ct<A>
{
    /// the representation can differ from that of the primary template
    A* mem;

public:
    A f()
    {
        return A {};
    }

    int g()
    {
        return int {};
    }

    void h(A)
    {
    }

    /// added functionality
    void k(int)
    {
    }
};


Ct<A> cta;      /// specialization for A
Ct<B> ctb;      /// specialization for B 


From Stroustrup's comment mentioned above, one might conclude it isn't possible to instantiate a class template on the heap. (After all, a template is instantiated at compile-time, whereas an allocation on the heap occurs at run-time.)

However, I have been able, easily, to instantiate this class template on the heap:

1
2
3
/// template instantiations on the heap ...
Ct<A>* pa {new Ct<A> {}};
Ct<B>* pb {new Ct<B> {}};


Therefore, I'm not very clear what Stroustrup's comment means.

Can anyone explain it?

Thanks.
I have been able, easily, to instantiate this class template on the heap

You instantiated an object of the class template Ct<A> and an object of class template Ct<B> on the heap and declared two pointers to them, cta and ctb respectively, that were created on the stack. You did not instantiate the class template itself, on the heap
Last edited on
He isn't saying it's impossible to place a instance of class template specialization on the heap, he's saying it's unnecessary, contrasting with dynamic polymorphism which expects heap allocation.
Topic archived. No new replies allowed.