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

前端 未结 4 2062
予麋鹿
予麋鹿 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:33

    In your approach you are forcing the allocator to be a template with a single parameter, which might not be always the case. In many cases, allocators can be non-template, and the nested rebind can return the same type of the allocator. In other cases the allocator can have extra template arguments. This second case is the case of std::allocator<> which as all templates in the standard library is allowed to have extra template arguments as long as the implementation provides default values. Also note that the existence of rebind is optional in some cases, where allocator_traits can be used to obtain the rebound type.

    The standard actually mentions that the nested rebind is actually just a templated typedef:

    §17.6.3.5/3 Note A: The member class template rebind in the table above is effectively a typedef template. [ Note: In general, if the name Allocator is bound to SomeAllocator, then Allocator::rebind::other is the same type as SomeAllocator, where someAllocator::value_type is T and SomeAllocator::value_type is U. — end note ] If Allocator is a class template instantiation of the form SomeAllocator, where Args is zero or more type arguments, and Allocator does not supply a rebind member template, the standard allocator_traits template uses SomeAllocator in place of Allocator:: rebind::other by default. For allocator types that are not template instantiations of the above form, no default is provided.

提交回复
热议问题