Is implicit casting with boost::any possible?

I'm curious if there's any way to get code like the following to work: boost::any a = char(10); int i = boost::any_cast<int>(a); More specifically, what I mean is, I'd like to be able to place a value of type T1 in 'a' and then retrieve it as type T2 which it can be implicitly cast to. Is this possible without the part that extracts the value from 'a' adding a lot of extra code to test all possibilities? What I would like to do is fill a map<string, any> with function pointers/objects/etc. and pass it to a function which casts the any values to slot types to connect to different signals whose type is determined at runtime. Basically something like this (but with MySig an unknown type until runtime). int func(char c, int i = 10); boost::any a = &func; typedef boost::signal<void (char)> MySig; MySig sig; sig.connect(boost::any_cast<MySig::slot_type>(a)); sig('j'); -jivera

(Second attempt to post) Matthew Dempsky wrote:
I'm curious if there's any way to get code like the following to work:
boost::any a = char(10); int i = boost::any_cast<int>(a);
You can customize boost::dynamic_any::any. Example: #include <string> #include <stdexcept> #include <iostream> #include <boost/mpl/list.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/dynamic_any/any.hpp> #include <boost/dynamic_any/function.hpp> #include <boost/dynamic_any/operations.hpp> // helper template<bool IsConvertible> struct convert_to_int { template<class T> static int do_convert(const T & value) { int result = value; return result; } }; template<> struct convert_to_int<false> { template<class T> static int do_convert(const T & value) { throw std::runtime_error(std::string("no convertion to int")); } }; // any to int convertion struct to_int : boost::dynamic_any::function< to_int, // curiously recurring pattern int (const boost::dynamic_any::arg &)> { template<class T> int call(const T & value) { typedef convert_to_int< ::boost::is_convertible<T, int>::value> converter; return converter::do_convert(value); } }; // customized any typedef boost::dynamic_any::any<boost::mpl::list< to_int, boost::dynamic_any::to_ostream<char> > > my_any; int main() { my_any a('a'); my_any b(3.14); std::cout << a << " -> " << to_int()(a) << '\n'; std::cout << b << " -> " << to_int()(b) << '\n'; } CVS access to the library: $ cvs -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/cpp-experiment login $ cvs -z3 -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/cpp-experiment co dynamic_any -- Alexander Nasonov Remove - m y c o p from my e-mail address for timely response
participants (2)
-
Alexander Nasonov
-
Matthew Dempsky