在我需要的简短版本中,我的代码看起来像这样
#include <vector>
template<typename T>
class Abstract {
public:
virtual void foo() = 0;
};
template<typename T>
class Collection {
public:
std::vector<Abstract<T>> items;
};
class Some {};
class Implementor : public Abstract<Some> {
public:
void foo() {
//...
}
};
int main() {
Collection<Some> *collection = new Collection<Some>;
Implementor *implementor = new Implementor;
collection->items.push_back(*implementor);
return 0;
}
编译器的判决是
抽象类类型'Abstract'的无效new-expression
错误全文:
In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\mingw32\bits\c++allocator.h:33:0,
from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\allocator.h:46,
from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\vector:61,
from D:\CLionProjects\test1\main.cpp:1:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\ext\new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = Abstract<Some>; _Args = {const Abstract<Some>&}; _Tp = Abstract<Some>]':
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\alloc_traits.h:455:4: required from 'static void std::allocator_traits<std::allocator<_Tp1> >::construct(std::allocator_traits<std::allocator<_Tp1> >::allocator_type&, _Up*, _Args&& ...) [with _Up = Abstract<Some>; _Args = {const Abstract<Some>&}; _Tp = Abstract<Some>; std::allocator_traits<std::allocator<_Tp1> >::allocator_type = std::allocator<Abstract<Some> >]'
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_vector.h:918:30: required from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Abstract<Some>; _Alloc = std::allocator<Abstract<Some> >; std::vector<_Tp, _Alloc>::value_type = Abstract<Some>]'
D:\CLionProjects\test1\main.cpp:27:45: required from here
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\ext\new_allocator.h:120:4: error: invalid new-expression of abstract class type 'Abstract<Some>'
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\CLionProjects\test1\main.cpp:4:7: note: because the following virtual functions are pure within 'Abstract<Some>':
class Abstract {
^~~~~~~~
D:\CLionProjects\test1\main.cpp:6:18: note: void Abstract<T>::foo() [with T = Some]
virtual void foo() = 0;
^~~
如何明确指定向量的类型?