Sign in to follow this  
Dragon_Strike

boost::any return its own type

Recommended Posts

i would like to replace this: if (pAny.type() == typeid(bool)) return SetValue(boost::any_cast<bool&>(pAny)); with something like this SetValue(boost::any_cast<pAny.type()&>(pAny)); // Which doesnt work is there anyway to get any_cast to return the type specified by type()?

Share this post


Link to post
Share on other sites
Nope; any_cast is a templated function. The types must be known at compile time.

If the collection of types you wanted to cast were all derived from some base, you could do some runtime factory-like indirection and save yourself some typing, but in that situation you probably wouldn't be using boost::any to begin with, and it's just a convient abstraction anyway.

Templates are compile-time creatures.

Share this post


Link to post
Share on other sites

template < class F > class AnyFunction;

template < typename R, typename T0 >
class AnyFunction< R (T0) > // 1 parameter, 1 return value, non-cost specialization
{
public:
template < R (*f)(T0) >
struct F {
R operator()( boost::any & p1 ) {
return f( boost::any_cast<T0>(p1) );
}
};
};




int SetValue( bool b ) <--- real function
{
...
}
AnyFunction< int (bool) >::F<&SetValue> SetValue;

...

boost::any a1(42);
boost::any a2(true);
boost::any a3("Hello World");

try {
SetValue( a1 );
SetValue( a2 );
SetValue( a3 );
} catch (boost::bad_any_cast &e) {
std::cout << e.what() << std::endl;
}




Edit: replaced with completely compile-time binding.

[Edited by - Antheus on January 2, 2008 11:38:53 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this