问题描述
每个分配器类都必须具有类似于以下界面的界面:
Every allocator class must have an interface similar to the following:
template<class T>
class allocator
{
...
template<class Other>
struct rebind { typedef allocator<Other> other; };
};
>
And classes that use allocators do something redundant like this:
template<class T, class Alloc = std::allocator<T> >
class vector { ... };
但是为什么这是必要的?
But why is this necessary?
换句话说,他们不能只是说:
In other words, couldn't they have just said:
template<class T>
class allocator { ... };
template<class T, template<class> class Alloc = std::allocator>
class vector { ... };
这是更优雅,更少冗余,并且(在某些类似情况下)可能更安全吗? >
为什么他们去了 rebind
路由,这也导致更多的冗余(即你必须说 T
两次)?
which is both more elegant, less redundant, and (in some similar situations) potentially safer?
Why did they go the rebind
route, which also causes more redundancy (i.e. you have to say T
twice)?
(类似的问题转到 char_traits
有 rebind
,他们仍然可以从模板模板参数中受益。)
(Similar question goes to char_traits
and the rest... although they don't all have rebind
, they could still benefit from template template parameters.)
其实很好用。
template<unsigned int PoolSize>
struct pool
{
template<class T>
struct allocator
{
T pool[PoolSize];
...
};
};
现在如果向量
:
template<class T, template<class> class Alloc>
class vector { ... };
然后你可以说:
typedef vector<int, pool<1>::allocator> int_vector;
它可以很好地工作,不需要你 int
两次。
And it would work perfectly well, without needing you to (redundantly) say int
twice.
而不是
Alloc :: template rebind< Other>
将会成为
Alloc< :: other
And a rebind
operation inside vector
would just become Alloc<Other>
instead of Alloc::template rebind<Other>::other
.
推荐答案
,第1卷,第4章, 35:
A quoted text from Foundations of Algorithms in C++11, Volume 1, chap 4, p. 35 :
template <typename T>
struct allocator
{
template <typename U>
using rebind = allocator<U>;
};
示例用法:
allocator<int>::rebind<char> x;
编辑 :在C ++编程语言中,第4版,第34.4.1节, 998,在默认分配器类中注释'classical'rebind成员:
EDIT : In The C++ Programming Language, 4th edition, section 34.4.1, p. 998, commenting the 'classical' rebind member in default allocator class :
template<typename U>
struct rebind { using other = allocator<U>;};
Bjarne Stroustupr写道:好奇的重新绑定模板是一个古老的别名,应该是: / p>
Bjarne Stroustupr writes this : "The curious rebind template is an archaic alias. It should have been:
template<typename U>
using other = allocator<U>;
但是,分配器是在C ++支持这样的别名之前定义的。
However, allocator was defined before such aliases were supported by C++."
这篇关于为什么当我们有模板模板参数时allocator :: rebind是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!