Boost python make_constructor with default arguments

I have a class that I want to pass using shared_ptr

. Thus, I want it to be created with a factory method:

py::class_<MyClass, boost::shared_ptr<MyClass>>("MyClass")
    .def("__init__", py::make_constructor(MyClass::factory))
;

      

It worked when it factory()

just took 2 arguments. But now I want it to take 2 or 3. So I used the overload macro

BOOST_PYTHON_FUNCTION_OVERLOADS(MyClass_factory_overloads, MyClass::factory, 2, 3)

      

But how do you convey this to make_constructor

?

+3


source to share


1 answer


I don't think you need to use a factory to create a shared_ptr of MyClass. So, just define a few init statements:

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);
}

      



Let's 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

      

+2


source







All Articles