STL 中的所有分配器感知类模板都必须使用分配器类型进行实例化。如果分配器不是 template 参数而是 template template 参数,对用户来说不是更方便吗?
为了演示,std::vector 和 std::basic_string 类模板分别具有以下签名:
template<class T, class Allocator = std::allocator<T>> class vector;
template<class CharT, class Traits = std::char_traits<CharT>, class Allocator = std::allocator<CharT>> class basic_string;
如果我有自定义分配器:
template <typename T>
class MyAllocator
{
// ...
};
并且想要实例化一个字符串 vector ,它使用我的自定义分配器来为 vector 和字符串的内部字符数组分配内部存储,事情很快就变得尴尬了:
typedef std::vector<std::basic_string<char, std::char_traits<char>, MyAllocator<char> >, MyAllocator<std::basic_string<char, std::char_traits<char>, MyAllocator<char>>>> CustomAllocStringVector;
使用额外的 typedef,这可以稍微简化:
typedef std::basic_string<char, std::char_traits<char>, MyAllocator<char>> CustomAllocString;
typedef std::vector<CustomAllocString, MyAllocator<CustomAllocString>> CustomAllocStringVector;
但困扰我的是,为什么要强制用户明确指定分配器的完整类型?如果我将分配器用于 char vector ,难道不应该说分配器将是 allocator<char> 类型吗?
如果 std::vector 和 std::basic_string 的签名是:
template<typename T, template <typename ElementType> class AllocatorType = std::allocator> class vector;
template<typename CharT, typename Traits = std::char_traits<CharT>, template <typename ElementType> class AllocatorType = std::allocator> class basic_string;
与上面相同的 vector 类型可以更简单地定义为:
typedef std::basic_string<char, std::char_traits<char>, MyAllocator> CustomAllocString;
typedef std::vector<CustomAllocString, MyAllocator> CustomAllocStringVector;
当然,我的方式要求所有分配器都是模板,但是任何应该至少可以重用的分配器类都必须满足此要求吗?
我确信这是有充分理由的,但目前我还没有看到。
最佳答案
这将引入一个要求,即分配器类型是一个类模板,只有一个模板参数,专门用于容器的 value_type
。你的建议将消除
template<typename T, unsigned int PoolNumber = 0>
class my_allocator;
作为一个有效的分配器。
同时,我可以简单地使用我已经拥有的typedef
作为我的分配器类型,不需要拆开它或重复它的模板名称:
template<typename T> class my_allocator;
typedef my_allocator<int> int_allocator;
std::list<int, int_allocator> ... // valid currently, difficult to express with your proposal
关于c++ - 在分配器感知的 STL 类中,为什么分配器不是模板模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25572251/