On 08/16/2011 12:43 PM, Grant Tang wrote:
This is a question about using implicitly_convertible to convert vector
to another custom class type.

I already have boost python type conversion code to convert Python
list/tuple to c++ vector, which works fine. There is another custom
class EMObject, which is a thin wrapper to many builit-in type. It takes
a built-in type like int, float, string, and vector as a single
constructor argument and return type. So those built-in type can convert
to and from EMObject implicitly. The functions in c++ which takes this
EMObject as an argument are expose to Python. Now I need call these
functions in Python with argument from Python list or tuple. Since I
already convert python list/tuple to c++ vector, I just need declare
implicit type conversion from vector to EMObject like following:

implicitly_convertible<vector<float>, EMAN::EMObject>();
implicitly_convertible<vector<int>, EMAN::EMObject>();
implicitly_convertible<vector<std::string>, EMAN::EMObject>();

This seems a perfect solution to my question. But unfortunately I find
out only the first one working, regardless which one is the first. Could
anybody tell me why this happen?


Unfortunately, there's no "best-match" type checking in Boost.Python; when trying to convert a Python object to a particular C++ type, it simply runs over a list of all the converters registered (using RTTI) for that C++ type.

Each of those converters then gets a chance to check whether it "matches" the Python object; if it thinks it does, none of the other converters get tried.

I'd guess that's what's happening to you - implicitly_convertible doesn't really do enough work in that match stage, so the first conversion you've registered says "I match!" and then fails by throwing an exception.

The fix might be in how you've written your vector<> conversions; when given a list or tuple that contains the wrong element type, they need to report that they "don't match", rather than matching any list or tuple and then throwing an exception when the element type is incorrect.

Good luck!

Jim Bosch
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to