template confusion

I was reading about custom allocators:
http://www.tantalon.com/pete/customallocators.ppt
I don't understand purpose of this part:
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
class allocator
{
public:
...
// what is the purpose for this struct in allocator class
template <class U>
struct rebind
{
     typedef allocator<U> other;
};
...
};


on this:
1
2
3
4
allocator<T> a;
T* t = a.allocate(1);
allocator<T>::rebind<N>::other na;
N* n = na.allocate(1);


any special reason they use this? as this can be written:
1
2
3
4
allocator<T> a;
T* t = a.allocate(1);
allocator<N> na;
N* n = na.allocate(1);


Thanks for your time.
Last edited on
It looks like the author is demonstrating the kind of thing that is possible with Templates. Or he's just showing off.
I don't think so, rebind is part of "default" STL allocator. I just don't see point for its existance.
I just read the presentation. Nice. Let me see if I can answer.

There are containers in STL that are of type T but don't allocate objects of type T. The example in the presentation is list. list<T> allocates nodes, as in a linked list. The class of this node, however, is private (I don't see it documented in this site anywhere), so you can't really say:

list<MyClass, MyAlloc<std::listnode<MyClass>>> myList;

So in order to solve this problem, the rebind construct is used. The rebind struct allows the std::list class to obtain an allocator of a different type to allocate the nodes.

And I think that should be it. I'm not 100% sure if the real reason is that listnode is private, or simply this is a construct devised to simplify the syntax.
Thanks greatly. If someone else has more opinions please share.
Topic archived. No new replies allowed.