为什么分配器类型作为模板参数而不是ctor的参数?

时间:2014-07-05 04:24:11

标签: c++ templates design-patterns standards allocator

#include <vector>

template<class T>
struct allocatorA: public std::allocator<T> {};

template<class T>
struct allocatorB: public std::allocator<T> {};

int main() 
{    
    std::vector<int, allocatorA<int>> c1;
    std::vector<int, allocatorB<int>> c2;

    c1 = c2; // error! counter-intuitive and gratuitous
}

但是,如果我们将allocator类型从template参数移动到构造函数的参数,那么代码更直观,更具表现力,如下所示:

步骤1:为所有分配器类定义通用接口

template<class T>
struct IAllocator
{
    virtual ~IAllocator();      
    // other stuff like std::allocator
};

template<class T>
struct MyAllocator : IAllocator {};

第2步:定义容器类

template<class T>
struct MyVector
{
    template<class allocatorT>
    MyVector(allocatorT alloc = MyAllocator<T>())
    : _alloc(new allocatorT(alloc)) 
    // can be optimized here. This is just a poc
    {}

    // other stuff like std::vector

    T* _internal_buf;
    IAllocator* _internal_alloc;
};

步骤3:定义两个不同的分配器类

template<class T>
struct allocatorX: public MyAllocator<T> {};

template<class T>
struct allocatorY: public MyAllocator<T> {};

第4步:愉快地使用MyVector

int main() 
{    
    MyVector<int> c3(allocatorX<int>());
    MyVector<int> c4(allocatorY<int>());

    c3 = c4; // OK
}

1 个答案:

答案 0 :(得分:0)

您在步骤1中的假设,即您要求所有分配器都来自相同类型,并不一定适用于所有情况。

相关问题