[C++-sig] Solution: overloaded constructor, problem with int and bool

Wolfgang Langner wl at flexis.de
Thu Sep 30 12:50:13 CEST 2004


Hello,


>>I have a C++ class that can be initialized with (double, int and bool).
>>With the following constructor it's not possible to init with a bool value:
>>
>>class_<Value>("Value")
>>       .def(init<>())
>>       .def(init<double>())
>>       .def(init<bool>())
>>       .def(init<int>());
>>
>>Because int is the last entry and it wins.
>>Bool constructor is never called.
>>example:
>>v = Value(False)
>>-> v = Value(0) and int constructor is called
>>
>>Is there a way to get this working ?

> Someday this will be better.  In the meantime, one approach you can
> take is to use an injected constructor that takes a
> back_reference<int> parameter, and then inspect the original PyObject*
> to see if its type was Bool.
> 

Thanks, this was the right hint for me.

Tested Version:

   // injected constructor
   Value* make_Value(back_reference<int> x)
   {
     if (x.source().ptr()->ob_type == &PyBool_Type) {
      return new Value(x.get() != 0);
     }
     else {
       return new Value(x.get());
     }
   }

   ...

   .def(init<double>())
   .def("__init__", make_constructor(make_Value))


I hope this helps other people too.


bye by Wolfgang




More information about the Cplusplus-sig mailing list