Boost :: any_cast - throw only when implicit conversion is not available?

I want boost::any_cast<T> throw an exception only when the type any does not have an implicit conversion to T The usual behavior seems to be to throw an exception if the type any not T , regardless of the implicit conversions.

Example:

 boost::any a = 1; boost::any_cast<int>(a); // This succeeds, and rightfully so boost::any_cast<long>(a); // I don't want this to throw boost::any_cast<Widget>(a); // I want this to throw 

Can someone tell me if there is an easy way to get the functionality I want, or better yet give me a good reason why the existing behavior is the way it is?

+4
source share
2 answers

Well, you can't do that. The any mechanism works as follows:

 struct base { virtual ~base() { } }; template<typename T> struct concrete_base : base { T t; concrete_base(T t):t(t) { } }; struct my_any { base * b; template<typename T> my_any(T t):b(new concrete_base<T>(t)) { } template<typename T> T any_cast() { concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b); if(!t) throw bad_any_cast(); return t->t; } }; 

I hope it is clear what this does. It is impossible to do what you are looking for, I think. The reason is that there is no type information that may be useful here. RTTI does not provide it.

+5
source

any_cast cannot do this, but if the base and derived types are completed (usually they are for types that are in the hierarchy), you can implement your own system, which is converted using throw and catch, since throwing a pointer to the derived type can be understood as base pointer type.

-1
source

All Articles