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

David Abrahams dave at boost-consulting.com
Wed Sep 29 18:50:20 CEST 2004


Wolfgang Langner <wl at flexis.de> writes:

> 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 ?
>
> I tried to change the order and got other strange results.
> With order
>
>        .def(init<int>())
>        .def(init<bool>())
>        .def(init<double>());
>
> all initializations with int are converted to use the double constructor.
> v = Value(10) results in a call to the double constructor and Value
> has the wrong type.
>
> Search trough documentation and Mailing list returned no results.

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.

// untested
Value* make_value(back_reference<int> x)
{
   if (x.source().ptr()->ob_type == PyBool_Type)
        return new Value(x != 0);
   else
        return new Value(x);
}


    ...
        .def(init<double>)
        .def(make_constructor(make_value))

HTH,
-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com




More information about the Cplusplus-sig mailing list