Why is `boost::any` better than `void*`?

Paul Manta picture Paul Manta · Jan 6, 2012 · Viewed 7.3k times · Source

What inherent advantages do boost::any and boost::any_cast offer over using void* and dynamic_cast?

Answer

Armen Tsirunyan picture Armen Tsirunyan · Jan 6, 2012

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)