我有一个类,我想通过 shared_ptr
传递。因此,我希望使用工厂方法构建它:
py::class_<MyClass, boost::shared_ptr<MyClass>>("MyClass")
.def("__init__", py::make_constructor(MyClass::factory))
;
这在 factory()
只接受 2 个参数时有效。但是现在我想要它取 2 或 3。所以我使用了重载宏
BOOST_PYTHON_FUNCTION_OVERLOADS(MyClass_factory_overloads, MyClass::factory, 2, 3)
但是我如何将它传递给 make_constructor
?
最佳答案
我认为您不需要使用工厂来创建 MyClass 的 shared_ptr。所以,只需定义多个 init 指令:
class Foo {
public:
Foo(int, int) { std::cout << "Foo(int, int)" << std::endl; }
Foo(int, int, int) { std::cout << "Foo(int, int, int)" << std::endl; }
};
void test(boost::shared_ptr<Foo>& foo) { std::cout << &(*foo) << std::endl; }
BOOST_PYTHON_MODULE(mylib)
{
using namespace boost::python;
class_<Foo, boost::shared_ptr<Foo> >("Foo", init<int, int>())
.def(init<int, int, int>())
;
def("test", test);
}
让我们测试一下:
import mylib
c2 = mylib.Foo(1,2)
Foo(int, int)
c3 = mylib.Foo(1,1,1)
Foo(int, int, int)
mylib.test(c2)
0x1521df0
mylib.test(c3)
0x1314370
c2a = c2
mylib.test(c2a)
0x1521df0 # the object has the same address of c2
关于python - 使用默认参数提升 python make_constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491098/