使用默认参数提升python make_constructor

时间:2014-12-15 18:54:46

标签: python c++ boost-python

我有一个我想要被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

1 个答案:

答案 0 :(得分:2)

我认为您不需要使用工厂来创建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