gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:10 24 4
gpt4 key购买 nike

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

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);

编译器对此提示:

Error 1 error C2664: 'Containers::BList::BList(Allocators::IAllocator &)' : cannot convert parameter 1 from 'Allocators::IAllocator *' to 'Allocators::IAllocator &' c:\licenta\licenta-transfer_ro-02may-430722\licenta\framework\framework\iallocator.h 21 Framework

我想我对这个有点过头了....

最佳答案

现有的答案是正确的,但是关于如何自己阅读错误的快速说明:你只需要将它分成几部分......

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 的引用>/li>
  • 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);

关于c++ - 使用模板容器的构造函数 C++ 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10414350/

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