What inherent advantages do boost::any
and boost::any_cast
offer over using void*
and dynamic_cast
?
The advantage is that boost::any
is way more type-safe than void*
.
E.g.
int i = 5;
void* p = &i;
static_cast<double*>(p); //Compiler doesn't complain. Undefined Behavior.
boost::any a;
a = i;
boost::any_cast<double>(a); //throws, which is good
As to your comment, you cannot dynamic_cast
from a void*
. You can dynamic_cast
only from pointers and references to class types which have at least one virtual function (aka polymorphic types)