What inherent advantages do boost::any
and boost::any_cast
offer over using void*
and dynamic_cast
?
Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
You can not increment a void pointer. Since a void* is typeless, the compiler can not increment it and thus this does not happen.
A void pointer is a pointer to incomplete type, so if either or both operands are void pointers, your code is not valid C. Note that GCC has a non-standard extension which allows void pointer arithmetic, by treating void pointers as pointer-to-byte for such cases.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With