std :: allocator_traits默认使用具有多个模板参数的allocator

Pra*_*tic 4 c++ templates allocator c++11 c++14

std::allocator_traits 当我提供一个具有单个模板参数的分配器的STL样式容器时,它会自动运行它的魔法,但是当我提供一个STL样式的容器时,它没有一个具有两个模板参数但其他类似的分配器.

std::allocator_traits如何与具有多个模板参数的分配器进行交互,我需要做什么?std::allocator_traits在这种情况下是否可以提供合理的默认值?

作为一个例子,如果我采用简单的分配器Howard HinnantAllocator Boilerplate中提供并将其提供给std::vector<>那么一切都很好.如果我intallocator模板添加一个虚拟参数(并根据需要进行轻微修改),那么我会遇到编译器错误,因为编译器无法找到rebind其他内容.

这是代码中的描述:

http://coliru.stacked-crooked.com/a/173c57264137a351

如果我必须std::allocator_traits在这种情况下专注自己,有没有办法仍然获得默认值?

Tem*_*Rex 7

标准仅为rebind具有多个模板类型参数的分配器提供默认值:

17.6.3.5分配器要求[allocator.requirements]

3注意A:rebind上表中的成员类模板实际上是一个typedef模板.[注意:在一般情况下,如果名称 Allocator绑定到SomeAllocator<T>,则 Allocator::rebind<U>::other是相同的类型SomeAllocator<U>,在这里SomeAllocator<T>::value_typeTSomeAllocator<U>:: value_typeU.- 结束注释]如果Allocator是表单的类模板实例化SomeAllocator<T, Args>,其中Args是零个或多个类型参数,并且Allocator不提供rebind成员模板,则标准allocator_traits模板默认使用SomeAllocator<U, Args>>代替Allocator:: rebind<U>::other.对于不是上述表单的模板实例化的分配器类型,不提供默认值.

由于您有一个非type(int)参数,因此没有提供默认值.修复很简单:只需将自己的重新绑定添加到分配器即可.

template<class T, int I>
class allocator_w_int
{
    // as before

    template<class U>
    struct rebind { using other = allocator_w_int<U, I>; };    
};
Run Code Online (Sandbox Code Playgroud)

实例

至于允许表单分配器Allocator<T, Args...>而不是表单分配器的基本原理Alloc<T, Ns...>,人们只能猜测,但随后它也会导致过多的Alloc<T, Args.., Ns...>等等.这就是模板元编程库(如Boost)的原因名为.mpl)总是包裹他们的非类型参数的N类型T里面的东西一样integral_constant<T, N>.通过定义,这也是一条适合您的路线

template<class T, class Arg>
class allocator_w_int; // leave undefined

template<int N>
using int_ = std::integral_constant<int, N>;

template<class T, int I>
class allocator_w_int<T, int_<I>>
{
    // replace all occurances of I, J --> int_<I>, int_<J>
};
Run Code Online (Sandbox Code Playgroud)

实例