相关疑难解决方法(0)

当我们有模板模板参数时,为什么需要allocator :: rebind?

每个allocator类必须具有类似于以下内容的接口:

template<class T>
class allocator
{
    ...
    template<class Other>
    struct rebind { typedef allocator<Other> other; };
};
Run Code Online (Sandbox Code Playgroud)

使用分配器的类做了多余的事情:

template<class T, class Alloc = std::allocator<T> >
class vector { ... };
Run Code Online (Sandbox Code Playgroud)

但为什么这有必要呢?

换句话说,他们不能只是说:

template<class T>
class allocator { ... };

template<class T, template<class> class Alloc = std::allocator>
class vector { ... };
Run Code Online (Sandbox Code Playgroud)

哪个更优雅,更少冗余,(在某些类似的情况下)可能更安全?
他们为什么要走这rebind条路,这也会造成更多的冗余(即你要说T两次)?

(类似的问题char_traits和其他问题......尽管它们并非都有rebind,但它们仍然可以从模板模板参数中受益.)


编辑:

但是,如果您需要多于1个模板参数,这将无效!

实际上,它运作得很好!

template<unsigned int PoolSize>
struct pool
{
    template<class T>
    struct allocator
    {
        T pool[PoolSize];

        ... …
Run Code Online (Sandbox Code Playgroud)

c++ templates allocator template-templates

26
推荐指数
3
解决办法
1万
查看次数

标签 统计

allocator ×1

c++ ×1

template-templates ×1

templates ×1