如果有一个allocator类型a1,对应于另外一个value_type的类型是typename a1::template rebind<x2>::othere[注2]。正如你能将一个类型转换为另外一个,模板的转换用构造函数让你转换值:你可以写malloc_allocator<int>(a),无论a的类型是malloc_allocator<int>,或malloc_allocator<double>,或malloc_allocator<string>。象往常一样,malloc_allocator的转换用构造函数用不着做任何事,因为malloc_allocator没有成员变量。
附带一提,虽然绝大多数的allocator有一个模板参数(allocator的value_type),但这不是需求中的规定,只不过常常正巧如此。重绑定机制在多模板参数的allocator上也工作良好:
template <class t, int flags> class my_allocator
{
public:
template <class u>
struct rebind { typedef my_allocator<u, flags> other; };
...
};
最后,最后一个细节:对于void我们该怎么做?有时一个容器必须涉及void的指针(再一次,我们将会在下一段落研究细节),而重绑定机制几乎给了我们所需要的东西,但并不完全。它不能工作,因为我们会写出类似malloc_allocator<void>::pointer的代码,而我们定义的malloc_allocator用void实例化时是非法的。它使用了sizeof(t),和涉及了t &;当t是void时,这两个都是非法的。解决的方法如同问题本身一样简单:为void特化malloc_allocator,扔掉其它一切,只留下我们需要的void的指针。
template<> class malloc_allocator<void>
{
typedef void value_type;
typedef void* pointer;
typedef const void* const_pointer;
template <class u>
struct rebind { typedef malloc_allocator<u> other; };
就是它了!malloc_allocator的完备源码见listing 1。