Jam*_*ook 2 c++ containers boost casting shared-ptr
我有一个方法
void foo(list<shared_ptr<Base>>& myList);
Run Code Online (Sandbox Code Playgroud)
我试图使用两种不同类型的列表调用,其中一个是DerivedClass1,另一个是DerivedClass2
list<shared_ptr<DerivedClass1>> myList1;
foo(myList1);
list<shared_ptr<DerivedClass2>> myList2;
foo(myList2);
Run Code Online (Sandbox Code Playgroud)
但是,这显然会产生编译器错误
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>>>"
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来转换shared_ptr的容器?可以实现这一目标的备用容器?
更新:感谢所有回复的人.在语言的限制范围内工作,似乎是保持方法"按原样"的最佳方法是使用shared_ptr的容器并准确传递(在调用站点创建新列表).
我想我几乎已经知道了这一点,但是我记得读过有关shared_ptr容器的boost库的其他部分,并且想到也许已经被其他人更优雅地解决了.从我自己的进一步研究来看,这些似乎更倾向于在多个指针独占拥有的情况下减少shared_ptr的开销(因此每个容器需要一个锁而不是容器中每个对象一个).
再次感谢,你们都很棒!
进行更改foo,使其遵循STL约定并获取迭代器:
template< typename It >
void foo(It begin, It end);
Run Code Online (Sandbox Code Playgroud)
然后将迭代器传递到列表中
list<shared_ptr<DerivedClass1>> myList1;
foo(myList1.begin(), myList1.end());
list<shared_ptr<DerivedClass2>> myList2;
foo(myList2.begin(), myList2.end());
Run Code Online (Sandbox Code Playgroud)
一切都应该工作得很好.
编辑:
请注意,这对智能指针并不特别.Astd::list<T1*>&无法用a初始化std::list<T2*>,即使T2派生自T1.
| 归档时间: |
|
| 查看次数: |
2819 次 |
| 最近记录: |