2016-04-10 60 views
1
纯虚拟类

继承当使用从升压Python模块在纯虚类派生类,我收到以下错误:升压Python从

allocating an object of abstract class type

没有升压Python模块,该误差不当下。在下面的例子中(接近我的用例),会有什么问题?我是否必须让Python意识到BaseDerived之间的继承关系?

PythonMinimal.cpp

#include <boost/python.hpp> 
#include <vector> 
using namespace boost::python; 

//Base class - pure virtual. 
template<typename T> 
class Base{ 
public: 
virtual void foo() = 0; 
}; 

//Derived class, inherites from Base. 
template<typename T> 
class Derived : public Base<T>{ 
public: 
    Derived(int a, int b){ 
     //Do something. 
    } 

    void foo(){ 
     //Do something else. 
    } 
}; 

//Test class, uses instances of Derived stored in STL container of Base. 
template<typename T> 
class TestClass{ 
public: 
    std::vector< Base<T> > vec; 

    TestClass(int a, int b){ 
     vec.push_back(Derived<T>(a, b)); 
    } 

    void foo(){ 
     vec.at(0).foo(); 
    } 
}; 

//Build python module. 
BOOST_PYTHON_MODULE(cpuMLP){ 
    class_< TestClass<float> >("TestClass", init<int, int>()) 
     .def("foo", &TestClass<float>::foo); 
}; 

的CMakeLists.txt

#Set CMake Version and project name. 
cmake_minimum_required(VERSION 2.8) 
project(PythonMinimal) 

#Attempt to find Python and Boost Python. 
find_package(PythonInterp) 
find_package(PythonLibs) 
find_package(Boost COMPONENTS python) 

#Find includes. 
include_directories(${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS}) 

#Add library to project. 
add_library(PythonMinimal SHARED PythonMinimal.cpp) 
target_link_libraries(PythonMinimal ${Boost_LIBRARIES} ${PYTHON_LIBRARIES}) 

回答

2

这是在所有的(你不暴露任何BaseDerived到Python)不相关的蟒蛇,问题出在你的vector

std::vector< Base<T> > vec; 

Base<T>是一个抽象类,你持有的。这是行不通的。您需要通过指针将它们存储:

std::vector<std::unique_ptr<Base<T>>> vec; 

这样,你不切片你Derived<T>对象。

+0

当然,这对我来说应该是显而易见的!现在我感到很傻。谢谢! –