gpt4 book ai didi

c++ - std::allocator_traits 默认为具有多个模板参数的分配器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:27:39 37 4
gpt4 key购买 nike

std::allocator_traits当我提供一个带有单个模板参数的分配器的 STL 样式容器时,它会自动发挥它的魔力,但当我提供一个带有两个模板参数但其他方面相似的分配器的 STL 样式容器时,它不会自动发挥作用。

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

例如,如果我采用 Howard Hinnant 在 Allocator Boilerplate 中提供的简单分配器并将其提供给 std::vector<>那么一切都很好。如果我添加一个虚拟 int allocator 的参数模板(并根据需要进行轻微修改)然后我得到编译器错误,因为编译器找不到 rebind ,等等。

这是代码中的描述:

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

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

最佳答案

标准只提供默认的rebind对于具有多个模板 type 参数的分配器:

17.6.3.5 Allocator requirements [allocator.requirements]

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<T>, then Allocator::rebind<U>::other is the same type as SomeAllocator<U>, where SomeAllocator<T>::value_type is T and SomeAllocator<U>::
value_type
is U. — end note ] If Allocator is a class template instantiation of the form SomeAllocator<T, Args>, where Args is zero or more type arguments, and Allocator does not supply a rebind member template, the standard allocator_traits template uses SomeAllocator<U, Args> > in place of Allocator:: rebind<U>::other by default. For allocator types that are not template instantiations of the above form, no default is provided.

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

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

template<class U>
struct rebind { using other = allocator_w_int<U, I>; };
};

Live Example

关于允许 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>
};

Live Example

关于c++ - std::allocator_traits 默认为具有多个模板参数的分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861283/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com