[C++-sig] Something like boost::any ... custom conversions?

Alex Mohr amohr at pixar.com
Thu Nov 17 19:22:20 CET 2005

> You can do it for specific held types just by registering the
> appropriate from_python converters:

Actually, I'm trying something like the code below now and it seems to 
be working so far.  I haven't tested extensively yet.  I'll have to 
register on the order of 100 converters like this and I'm wondering how 
much it might affect performance.

Is this a reasonable approach?  Is there a better way?  Is there some 
gap in my understanding?  Any comments are greatly appreciated.


// In this code, MyAny is a boost::any like object which has methods
// isHolding<T>() and get<T>()
using namespace boost::python;

template <typename T>
static void *convertible(PyObject *obj_ptr)
	extract<MyAny> getAny(obj_ptr);
	if (getAny.check()) {
		MyAny a = getAny();
		if (a.isHolding<T>())
			return obj_ptr;
	return 0;

template <typename T>
static void construct(PyObject *obj_ptr,
	converter::rvalue_from_python_stage1_data *data)
	MyAny a = extract<MyAny>(obj_ptr);
	if (!a.isHolding<T>())
		// throw an exception: type error.
	void *storage =
	new (storage) T(a.get<T>());
	data->convertible = storage;

// Then I register converters like this
converter::registry::push_back(convertible<T>, construct<T>,

More information about the Cplusplus-sig mailing list