gpt4 book ai didi

c++ - 类型转换 shared_ptr 的容器

转载 作者:太空狗 更新时间:2023-10-29 23:38:01 24 4
gpt4 key购买 nike

我有一个方法

void foo(list<shared_ptr<Base>>& myList); 

我试图用两种不同类型的列表调用,一种是 DerivedClass1,另一种是 DerivedClass2

list<shared_ptr<DerivedClass1>> myList1; 
foo(myList1);
list<shared_ptr<DerivedClass2>> myList2;
foo(myList2);

但是这显然会产生编译错误

error: a reference of type "std::list<boost::shared_ptr<Base>, std::allocator<boost::shared_ptr<Base>>> &" (not const-qualified) cannot be initialized with a value of type "std::list<boost::shared_ptr<DerivedClass1>, std::allocator<boost::shared_ptr<DerivedClass1>>>"

有没有简单的方法来转换 shared_ptr 的容器?可以实现此目的的替代容器?

更新:感谢所有回复的人。在语言的范围内工作,在保持方法“原样”的同时,最好的方法似乎是使用 shared_ptr 的容器并准确地传递它(在调用站点创建一个新列表)。

我想我几乎已经知道了这一点,但我记得读过有关处理 shared_ptr 容器的 boost 库的其他部分的内容,并认为也许其他人已经更优雅地解决了这个问题。然而,根据我自己的进一步研究,这些似乎更适合在许多指针被排他拥有的情况下减少 shared_ptr 的开销(因此每个容器需要一个锁,而不是容器中的每个对象一个锁)。

再次感谢,你们都很棒!

最佳答案

更改 foo以便它遵循 STL 约定并采用迭代器:

template< typename It >
void foo(It begin, It end);

然后将迭代器传递到您的列表中

list<shared_ptr<DerivedClass1>> myList1;
foo(myList1.begin(), myList1.end());
list<shared_ptr<DerivedClass2>> myList2;
foo(myList2.begin(), myList2.end());

一切都应该工作得很好。

编辑:
请注意,这对智能指针来说并不是什么特别之处。 std::list<T1*>&不能用 std::list<T2*> 初始化, 即使T2源自 T1 .

关于c++ - 类型转换 shared_ptr 的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2782092/

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