每个分配器类必须具有类似于以下的接口:
template<class T>
class allocator
{
...
template<class Other>
struct rebind { typedef allocator<Other> other; };
};
和课程use分配器做了一些多余的事情,如下所示:
template<class T, class Alloc = std::allocator<T> >
class vector { ... };
但为什么这是必要的呢?
换句话说,他们就不能说:
template<class T>
class allocator { ... };
template<class T, template<class> class Alloc = std::allocator>
class vector { ... };
哪个更优雅,更少冗余,并且(在某些类似情况下)可能更安全?
他们为什么去rebind
路线,这也会导致更多冗余(即你必须说T
twice)?
(类似的问题去char_traits
其余的......虽然他们并不都有rebind
,他们仍然可以从模板模板参数中受益。)
Edit:
但如果您需要超过 1 个模板参数,这将不起作用!
事实上,它的效果非常好!
template<unsigned int PoolSize>
struct pool
{
template<class T>
struct allocator
{
T pool[PoolSize];
...
};
};
Now if vector
仅这样定义:
template<class T, template<class> class Alloc>
class vector { ... };
那么你可以直接说:
typedef vector<int, pool<1>::allocator> int_vector;
而且它会完美地工作,without需要你(多余地)说int
twice.
And a rebind
内部操作vector
就会变成Alloc<Other>
代替Alloc::template rebind<Other>::other
.