簡體   English   中英

在boost.python中使用抽象類時無法使用純虛函數

[英]Cannot use pure virtual functions in my abstract class when using it in boost.python

我正在嘗試使用我的C ++庫擴展Python,並且在這種特殊情況下遇到了一些問題:假設有一個名為Shape的抽象類,現在我想允許Python從Shape繼承並基本上實現其自己的Shape ,但還可以在C ++代碼中使用Shape的某些現有實現。 讓我顯示一些代碼:

class Shape {
public:
    virtual inline double get_area() const = 0;
};

太好了,現在我們說有一個名為Circle的C ++類。

class Circle : public Shape {
public:
    Circle() = default;
    inline double get_area() const override { return 0.5; }
}

好的,讓我們為Shape (版本1)編寫一個包裝器:

struct ShapeWrap : public Shape, public wrapper<Shape>{
   inline double get_area() const override {
      if (auto py_func = this->get_override("get")) return py_func();
      return Shape::get_area();
   }
   inline double default_get_area() const {
      return this->Shape::get_area();
   }
};

然后以這種方式定義Shape:

class_<ShapeWrap, boost::noncopyable>("Shape")
        .def("get_area", &Shape::get_area, &ShapeWrap::default_get_area));

好的,現在這是一個問題,因為Shape是一個抽象類,並且理所當然地,它沒有實現get_area (它是純虛擬的)。 好吧,我們如何將所有這些抓取並以這種方式編寫呢?

struct ShapeWrap : public Shape, public wrapper<Shape>{
   inline double get_area() const override {
      if (auto py_func = this->get_override("get")) return py_func();
      return 0.0;
   }
};

然后像這樣定義Shape

class_<ShapeWrap, boost::noncopyable>("Shape")
        .def("get_area", pure_virtual(&ShapeWrap::get_area));

好的,這對於Python覆蓋的對象來說效果很好。 但是,如果我在Python中創建Circle對象,則會出現以下錯誤:

Boost.Python.ArgumentError: Python argument types in
    Shape.get_area(Circle)
did not match C++ signature:
    get_area(ShapeWrap {lvalue})
    get_area(ShapeWrap {lvalue})

現在,如果我在Shape類中使get_area返回0.0作為默認行為,但是如果我不想僅以支持Python的方式編寫API,則所有這些問題都將得到解決,我想為當函數不可用並僅對Python返回0.0時,因為抽象類的概念在Python中不存在,這很好,但是接下來我將把Shape作為其余部分的抽象類C ++ API。 有什么辦法嗎?

感謝@llonesmiz,我意識到問題在於將包裝器函數傳遞給了純虛函數。 ShapeWrapper這種方式定義ShapeWrapper可以解決此問題:

class_<ShapeWrap, boost::noncopyable>("Shape")
    .def("get_area", pure_virtual(&Shape::get_area));

暫無
暫無

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

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