简体   繁体   English

促进Python从纯虚拟类继承

[英]Boost Python Inheriting from Pure Virtual Class

When using a derived class from a pure virtual class in a Boost Python module, I am receiving the following error: 在Boost Python模块中使用从纯虚拟类派生的类时,出现以下错误:

allocating an object of abstract class type 分配抽象类类型的对象

Without the Boost Python module, the error is not present. 没有Boost Python模块,该错误将不存在。 In the following example(close to my use case), what would be the issue? 在下面的示例(接近我的用例)中,问题是什么? Do I have to make Python aware of the inheritance relationship between Base and Derived ? 我是否必须使Python知道BaseDerived之间的继承关系?

PythonMinimal.cpp 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 的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})

This isn't related to python at all (you're not exposing either Base or Derived to python), the problem is in your vector : 这根本与python不相关(您没有将BaseDerived暴露给python),问题出在您的vector

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

Base<T> is an abstract class that you're holding values of. Base<T>是您持有其的抽象类。 That isn't going to work. 那是行不通的。 You need to store them by pointer: 您需要通过指针存储它们:

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

This way you're not slicing your Derived<T> objects. 这样,您就不会切片Derived<T>对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM