gpt4 book ai didi

c++ - 关于自定义分配器和 STL 的模板声明、别名和特化说明

转载 作者:太空狗 更新时间:2023-10-29 21:18:06 26 4
gpt4 key购买 nike

抱歉标题含糊不清,但我不知道哪个是正确的术语(即使可以执行以下操作)。

假设我在某处有一个模板类(分配器):

template<class Arena, typename T> Allocator
{
public:
Allocator(Arena a);
...
};

然后我有另一个类,它与 Allocator 有某种关系,但不能在实例化时专门化 T 参数。这个想法是为它声明一个“非专门化的别名”,并让专门化在其他地方。像这样的东西:

class MemoryArena
{
using Allocator<T> = AnAllocatorStrategy<T>; //not legal, but just to give the idea

void* Allocate(size_t);
};

用法应该是这样的:

Arena anArena(...);
Arena::Allocator<int> allocInt; // some way declare a specialization of the alias

std::vector<int, Arena::Allocator<int>> myVec(allocInt);

这背后的主要思想是,因为 STL 容器需要一个针对所包含元素类型的专用分配器,我仍然可以使用相同的内存区域并让专用实例转发分配调用给它。但我仍然希望 Arena 本身控制基本分配策略(最终还对未完全专门化的 AllocatorStrategy 进行参数化)。

有什么提示吗?这可能吗?


编辑

感谢评论,我以这种方式使用别名模板修复了声明:

class MemoryArena
{
template<typename T> using MyAllocatorTemplate = Allocator<MemoryArena, T>;;

void* Allocate(size_t);
};

我仍然需要弄清楚是否有可能使 Allocator 成为 MemoryArena 定义的一部分,而无需完全指定 T 参数。像这样的东西:

template<class AllocatorType<MemoryArena,?> = DefaultAllocType<MemoryArena,?>> //is possible not to specify T on MemoryArena definition?
class MemoryArena<AllocatorType>
{
template<typename T> using MyAllocatorTemplate = AllocatorType<MemoryArena,T>;

或者,任何其他建议都将受到赞赏。主要目标是让用户指定 Arena 的分配器类型,T 参数除外(仅对在容器内使用分配器有用)。

最佳答案

template<template<class...>class Z, class...T0s>
struct partial_apply {
template<class...T1s>
using result = Z<T0s...,T1s...>;
};
template<template<class...>class A, template<class...>class B>
struct same_template : std::false_type {};
template<template<class...>class A>
struct same_template<A,A> : std::true_type {};

template<class...>class Default {};
template<
template<class...>class AllocatorType=Default
>
class MemoryArena {
template<class T>
using MyAllocatorTemplate = std::conditional_t<
same_template<AllocatorType, Default>{},
DefaultAllocType<MemoryArena, T>,
AllocatorType<T>
>;
};

假设除了DefaultAllocType之外还有一些其他分配类型, OtherAllocType<Chicken, T> .然后:

template<class...Ts>
using OtherAllocChicken = partial_apply<OtherAllocType, Chicken>::template result<Ts...>;
using ChickenArena = MemoryArena< OtherAllocChicken >;

另一方面,如果您要求传递给传入模板的参数为 MemoryArena 有时,事情会变得更加复杂。

之前MemoryArena已参数化,类型不存在。所以你必须有某种占位符可以告诉你应该在哪里注入(inject)它。

如果你希望它永远是MemoryArena ,那么事情就更简单了:你已经有了那个解决方案:

template<template<class...>class AllocatorType = DefaultAllocType>
class MemoryArena {
template<typename T>
using MyAllocatorTemplate = AllocatorType<MemoryArena,T>;
};

关于c++ - 关于自定义分配器和 STL 的模板声明、别名和特化说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914094/

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