[C++-sig] boost::any

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Thu Feb 23 02:04:42 CET 2006

IIUC, for all user-defined types, Boost.Python searches for converters at
runtime, not at compile-time. However, conversion of built-in types is highly
optimized and the converters are actually determined at compile-time.

Couldn't you just do this?

  class_<boost::any>("boost_any", no_init);
  class<std::vector<boost::any> >("stl_vector_boost_any", no_init);

You couldn't manipulate these types from Python, but at least you can return a
boost::any from one function and use it as an argument in another. If you want
to be fancy, you could give boost_any some methods, e.g. to return the value
type name as a string or to convert certain types you know/care about to a
boost::python::object. E.g. (untested):

  any_extract(boost::any const& self)
    if (self.empty()) return boost::python::object(); // None
    if (self.type() == typeid(int)) {
      return boost::python::object(*boost::any_cast<int>(self));
    if (self.type() == typeid(double)) {
      return boost::python::object(*boost::any_cast<double>(self));
    throw std::runtime_error("boost::any: unkown value type");

  class_<boost::any>("boost_any", no_init)
    .def("empty", &boost::any::empty)
    .def("extract", any_extract)

Note that you can wrap an unbound C++ function as a Python method if the first
argument of the function is of the wrapped type.

You could even enable construction of any objects from Python by injecting your
custom constructor using boost::python::make_constructor.

If you want to manipulate the std::vector<boost::any> from Python you could
most likely use the vector indexing suite that comes with Boost.Python.

Unless I am overlooking something fundamental (I've never worked with
boost::any) I think you can make this work really nicely.


Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Cplusplus-sig mailing list