[C++-sig] Is there a way to automatically convert a smart_ptr to a held_type (try 2)

David Abrahams dave at boost-consulting.com
Thu Aug 31 04:53:28 CEST 2006


Alex Mohr <amohr at pixar.com> writes:

>> What I need is a way to tell boost python that anytime it needs to
>> convert a ptr<Base> to python it should first convert it to a
>> ref_ptr<Base>  (using a standard copy constructor in ref_ptr<>) and
>> then use this ref_ptr as the held type like normal.
>> 
>> At first I thought that implicitly_convertible<> would help:
>> 
>> implicitly_convertible<ptr<Base>, ref_ptr<Base> >();
>> 
>> But this doesn't seem to do anything for me. (this really isn't too
>> surprising since this isn't what implicitly_convertible is for, but it
>> seemed worth a try).
>> 
>> Has anyone else ran into anything similar?  Any ideas?
>
> At first glance, it seems like you want to register a to-python 
> conversion for all your ptr<T> types.  

Good idea.

> Note that all code I write in 
> this message is untested:
>
> template <class T>
> struct ptr_to_python {
>      static PyObject *convert(ptr<T> const &p) {
>          return Py_INCREF(object(ref_ptr<T>(p)).ptr());
>      }
> };
>
> Then you need to do this for each class you register:
>
> to_python_converter<ptr<T>, ptr_to_python<T> >();

Looks good so far.

> You could automate this in a custom def visitor:
>
> struct ref_ptr_stuff : def_visitor<ref_ptr_stuff> {
>      friend class def_visitor_access;
>      template <typename Class>
>      void visit(Class &c) const {
>          typedef typename Class::wrapped_type T;
>          to_python_converter<ptr<T>, ptr_to_python<T> >();
>      }
> };

That is a very clever and elegant abuse of def_visitor, I must say!

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list