如何用pybind11将模板方法模式的C++类导出到Python?
解决方案
核心思路是仅绑定最终的Derived具体类,无需暴露抽象基类或接口,pybind11会自动处理C++继承链的逻辑,完全满足你的需求。
具体实现步骤
1. 保留原有C++类结构
你的C++代码无需修改,示例结构如下:
#include <iostream> class Interface { public: virtual void process() = 0; virtual ~Interface() = default; }; class AbstractImpl : public Interface { public: void process() override { step1(); step2(); } protected: virtual void step1() = 0; virtual void step2() = 0; }; class Derived : public AbstractImpl { protected: void step1() override { std::cout << "Derived step1\n"; } void step2() override { std::cout << "Derived step2\n"; } };
2. 编写pybind11绑定代码
只需要绑定Derived类,且仅导出process方法即可,不需要任何虚函数相关的冗余宏:
#include <pybind11/pybind11.h> namespace py = pybind11; PYBIND11_MODULE(template_method, m) { py::class_<Derived>(m, "Derived") .def(py::init<>()) .def("process", &Derived::process); }
3. Python端调用验证
编译生成扩展模块后,Python中可直接实例化并调用方法:
import template_method d = template_method.Derived() d.process() # 输出: # Derived step1 # Derived step2
方案优势
- 封装性达标:protected的
step1/step2属于C++内部实现,Python无法访问,自然满足不导出的要求。 - 无冗余代码:不需要
PYBIND11_OVERRIDE_PURE这类宏,因为我们不需要在Python中重写虚函数,绑定代码简洁高效。 - 继承逻辑自动处理:pybind11会自动识别
Derived继承自AbstractImpl的process方法,无需手动处理接口调用逻辑。
内容的提问来源于stack exchange,提问作者user8510613
相关产品推荐
相关产品推荐

