簡體   English   中英

促進Python從純虛擬類繼承

[英]Boost Python Inheriting from Pure Virtual Class

在Boost Python模塊中使用從純虛擬類派生的類時,出現以下錯誤:

分配抽象類類型的對象

沒有Boost 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})

這根本與python不相關(您沒有將BaseDerived暴露給python),問題出在您的vector

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

Base<T>是您持有其的抽象類。 那是行不通的。 您需要通過指針存儲它們:

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

這樣,您就不會切片Derived<T>對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM