【发布时间】:2023-03-16 09:55:01
【问题描述】:
我想创建一个list<unique_ptr<Base>> listOfBaseUniquePtr。这将能够给我两个:
1.唯一的ptrs,和
2. 多态性。我应该能够调用每个派生类的虚函数。
有些东西对我不起作用。看看下面的代码示例:
#include <iostream>
#include <list>
#include <memory>
using namespace std;
class Base {
};
list<unique_ptr<Base>> listOfBaseUniquePtr;
template <typename T>
class Derived: public Base {
};
int main() {
listOfBaseUniquePtr.push_back(new Derived<int>()); // <--- error
}
错误:
main.cpp:19:53: 错误:没有匹配的调用函数
'std::list >::push_back(Derived)'
listOfBaseUniquePtr.push_back(new Derived()); // ^ main.cpp:19:53:注意:候选人是:在包含的文件中 /usr/include/c++/4.8/list:63:0,
来自 main.cpp:2: /usr/include/c++/4.8/bits/stl_list.h:1015:7: 注意: void std::list<_tp> _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr; _Alloc = std::allocator
std::list<_tp _alloc>::value_type = std::unique_ptr]
push_back(const value_type& __x)
^ /usr/include/c++/4.8/bits/stl_list.h:1015:7:注意:没有已知的参数 1 从“Derived”到“const value_type&
的转换 {又名 const std::unique_ptr&}'
/usr/include/c++/4.8/bits/stl_list.h:1020:7: 注意: void std::list<_tp> _Alloc>::push_back(std::list<_tp _alloc>::value_type&&) [with _Tp = std::unique_ptr; _Alloc = std::allocator
std::list<_tp _alloc>::value_type = std::unique_ptr]
push_back(value_type&& __x)
^ /usr/include/c++/4.8/bits/stl_list.h:1020:7:注意:没有已知的参数 1 从“派生*”到
的转换 'std::list >::value_type&& {aka
std::unique_ptr&&}' make[2]:
[CMakeFiles/uniqueptr.dir/main.cpp.o] 错误 1 make[1]:
[CMakeFiles/uniqueptr.dir/all] 错误 2 make: [all] 错误 2
我做错了什么?
【问题讨论】:
-
push_back(make_unique<Derived<int>>())应该可以完成这项工作。