boost::any
can hold values of any type, but you have to know what it can possibly hold to be able to extract the value and it allocates memory on the heap for the stored value.
boost::variant
on the other hand, can only store values of a set of specified types and you can easily find out what it holds, the sizeof
of boost::variant
is going to be the sizeof
of the largest value type it contains + some extra for the type of the stored value because it does not use heap memory (unless a recursive variant is used).
From memory usage standpoint of view boost::variant
may be more efficient because it does not use heap memory. Also, boost::variant
is more type-safe that boost::any
, the compiler can find more errors at compile time for you.