Why is allocator::rebind necessary when we have template template parameters?

前端 未结 4 2054
予麋鹿
予麋鹿 2020-11-27 17:07

Every allocator class must have an interface similar to the following:

template
class allocator
{
    ...
    template
    s         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-27 17:27

    Suppose you want to write a function taking all sorts of vectors.

    Then it is much more convenient being able to write

    template 
    void f (std::vector  vec) {
       // ...
    }
    

    than having to write

    template  class A>
    void f (std::vector  vec) {
       // ...
    }
    

    In most of the cases, such a function does not care about the allocator anyway.

    Further note that allocators are not required to be a template. You could write separate classes for particular types that need to be allocated.

    An even more convenient way of designing allocators would probably have been

    struct MyAllocator { 
       template 
       class Core {
          // allocator code here
       };
    };
    

    Then it would have been possible to write

    std::vector  vec;
    

    rather than the somewhat misleading expression

    std::vector  > vec;
    

    I am not sure whether the above MyAllocator is permitted to be used as an allocator after adding a rebind, i.e. whether the following is a valid allocator class:

    struct MyAllocator { 
       template 
       class Core {
          // allocator code here
       };
    
       template 
       struct rebind { using other=Core; };
    };
    

提交回复
热议问题