Boost.python got confused in a similar constructor

I have a class that looks like

class Foo{ Foo(); Foo(int i); Foo(bool b); Foo(double d); }; 

and I expose my class in python as usual

 class_<Foo>("Foo") .def(init<int>()) .def(init<bool>()) .def(init<double>()); 

when I try to use in python, the python code always distinguishes the c'tor parameter in double (which is always the last in the def export class). Is there a way to explicitly tell boost.python how to explicitly handle the type?

+6
source share
1 answer

Well, you can change the order of constructor definitions, the latter will have a higher priority. Here are my results:

 class_<Foo>("Foo") .def(init<bool>()) .def(init<double>()) .def(init<int>()); Foo() # calls Foo() Foo(True) # calls Foo(int) Foo(1) # calls Foo(int) Foo(4.2) # calls Foo(double) 

As you can see, this is not an ideal solution. Therefore, if you really need to do work with overloaded constructors, I suggest you run your own factory function.

 using namespace boost::python; static boost::shared_ptr<Foo> makeFoo(const object& data) { boost::shared_ptr<Foo> obj; if (PyBool_Check(data.ptr())) { bool val = extract<bool>(data); obj.reset(new Foo(val)); } else if (PyFloat_Check(data.ptr())) { double val = extract<double>(data); obj.reset(new Foo(val)); } else { int val = extract<int>(data); obj.reset(new Foo(val)); } return obj; } class_<Foo>("Foo") .def("__init__", make_constructor(makeFoo)); 

And using makeFoo:

 Foo() # calls Foo() Foo(True) # calls Foo(bool) Foo(1) # calls Foo(int) Foo(4.2) # calls Foo(double) 

By the way, docs on python.org can be somewhat useful.

+10
source

Source: https://habr.com/ru/post/901535/


All Articles