[C++-sig] boost::any

Christophe de Vienne cdevienne at alphacent.com
Wed Feb 22 20:59:11 CET 2006


Hi Jens !

Jens Finkhäuser wrote:

> Hi!
> 
>   The problem is that boost::python converters (please correct me if I'm
> wrong, it's been a while) are selected by the compiler at compile time
> based on the C++ type you want to convert from/to.

Which is why my idea was to provide such a converter for boost::any.
But I don't know if a 'generic' converter (ie using automaticaly the
specialised ones) is possible.


>   boost::any is pretty much the same as a python variable, though, and
> does not have a type related to the type of object it holds. Rather it can
> be thought of as an untyped reference to a typed object.
>   The held object has a distinct type such as std::string or int whereas
> boost::any stays boost::any regardless of what type of object it holds.
> Python variables are similar in that they are basically references to
> typed objects.
>   That means the C++ compiler can't determine at compile time what type
> of object a boost::any holds, and therefore not determine what type of
> python object to convert that held object to.

Yes, but as far as I understand, the type_id of the c++ types is used to
determine how to convert them from/to python objects. And this type_id
being available on boost::any, I am hoping that implementing such
converters is possible (if not easy enough for me).


>   If as you say you have a limited set of types that your boost::any
> holds, you might want to create a simple class hierarchy for them:
> 
>     struct foo_base {};
>     struct foo_str : public foo_base { std::string m_value; }
>     struct foo_int : public foo_base { int m_value; }
> 
>   Then you can code and register some trivial converters for foo_str,
> foo_int, etc. and hand around vector<shared_ptr<foo_base> > (or
> something equivalent) instead of vector<any>.

Getting rid of boost::any in my case is not trivial (but possible), as I
would have to touch quite a lot of code, but I could use this construction
as a temporary holder so boost::python knows how to handle everything.

It's an easy workaround. It seems to me that it's almost equivalent as to
hand-code a converter for boost::any which knows a finished set of types.
Does it make sense ?

>   To save you some typing, you could make foo_base a template:
>     template <typename heldT>
>     struct foo_base

In this case I cannot make a std::vector< shared_ptr<foo_base> >, but I get
the idea : 

template<typename heldT>
struct foo: foo_base
{
        // ...
};




Thanks !

Christophe





More information about the Cplusplus-sig mailing list