使用模板容器的构造函数c ++时遇到问题

时间:2012-05-02 13:04:22

标签: c++ templates

我尝试使用自定义容器,并在该容器的构造函数中传递内存池分配器。 整件事情就这样开始了:

AllocatorFactory alloc_fac;

//Creates a CPool allocator instance with the size of the Object class
IAllocator* object_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(Object));
//Creates a CPool allocator instance with the size of the BList<Object> class
IAllocator* list_alloc = alloc_fac.GetAllocator<CPool>(10,sizeof(BList<Object>));
//Same logic in here as well
IAllocator* node_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(BListNode<Object>));

IAllocator类看起来像这样:

 class IAllocator
{

public:

    virtual void* allocate( size_t bytes ) = 0;
    virtual void deallocate( void* ptr ) = 0;

    template <typename T>
    T* make_new()
    { return new ( allocate( sizeof(T) ) ) T (); }

    template <typename T, typename Arg0>
    T* make_new( Arg0& arg0 )
    { return new ( allocate( sizeof(T) ) ) T ( arg0 ); }

            .......
}

容器类的构造函数如下所示:

template <class T>
class BList {
......
public:
/**
 *@brief Constructor
 */
BList(Allocators::IAllocator& alloc){
     _alloc = alloc;
    reset();
    }
/**
 *@brief Constructor
 *@param inOther the original list
 */
 BList(const BList<T>& inOther){
    reset();
    append(inOther);
    }
.....
}

当我这样做时:

 BList<Object> *list = list_alloc->make_new<BList<Object>>(node_alloc);

编译器抱怨这个:

  

错误1错误C2664:&#39;容器:: BList :: BList(分配器:: IAllocator&amp;)&#39; :无法从&#39; Allocators :: IAllocator *&#39;转换参数1 to&#39; Allocators :: IAllocator&amp;&#39; c:\ licenta \ licenta-transfer_ro-02may-430722 \ licenta \ framework \ framework \ iallocator.h 21 Framework

我想我已经超越了这个......

3 个答案:

答案 0 :(得分:3)

现有答案是正确的,但请自行快速了解如何阅读错误:您只需要将其拆分成碎片......

Error 1 error C2664: 'Containers::BList::BList(Allocators::IAllocator &)' : cannot convert parameter 1 from 'Allocators::IAllocator *' to 'Allocators::IAllocator &'

读取:

  • 你正在调用Containers::BList::BList(Allocators::IAllocator &),这是一个带有一个参数的构造函数,一个对IAllocator的引用
  • cannot convert parameter 1表示编译器遇到第一个(也是唯一的)参数类型的问题
    • 你已经给出了这种类型:... from 'Allocators::IAllocator *'
    • 并且它想要这种类型(以匹配构造函数声明):... to 'Allocators::IAllocator &'

那么,你如何从指针转换为构造函数想要的引用?


好的,我也添加了实际答案:

Allocators::IAllocator *node_alloc = // ...
Allocators::IAllocator &node_alloc_ref = *node_alloc;
BList<Object> *list = list_alloc->make_new<BList<Object>>(node_alloc_ref);

或只是:

BList<Object> *list = list_alloc->make_new<BList<Object>>(*node_alloc);

答案 1 :(得分:1)

您似乎使用指针而不是引用来调用make_new。尝试:

BList<Object> *list = list_alloc->make_new<BList<Object>>(*node_alloc);

然后,请选择一个压痕窗框并坚持下去。

答案 2 :(得分:0)

您的allocator工厂正在返回指向分配器的指针,但您的构造函数需要对分配器的引用。你需要取消引用指针。

IAllocator* node_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(BListNode<Object>));    

// Instead of:
// BList<Object> mylist(node_alloc);
// you need:
//
BList<Object> mylist(*node_alloc);