Erase styles and optimize a small buffer.
You can erase almost any property in C ++ by creating a custom interface that βknowsβ how to apply the property to a type that is currently unknown.
boost::any type erases to copy, destroy, get typeid and type cast-back-to-exact-matching-type. std::function type erases before copying, is called with a certain signature, destruction and call back to the identical type (the latter is rarely used).
Free implementations of storage-based type erasure get the semantics of the move βfor free,β replacing pointers.
In your case, you need to create a "fairly large" aligned repository in the type. You want to type erase to copy, get-as-a-link-to-base, destroy, and probably move (since you store internally).
std::aligned_storage is for your task (you can pass alignment requirements for all types that you are going to store). Then a new object is in place.
Create a table of operations that you want to perform on the object via void* - copy, move, destroy and convert-to- base* .
template<class Sig>using f = Sig*; struct table { f<base*(void*)> convert_to_base; f<base const*(void const*)> convert_to_const_base; f<void(void*,void const*)> copy_construct; f<void(void*)> destroy; f<void(void*,void*)> move_construct; }; template<class T> table const* get_table() { static table t = {
now save get_table<T>() in your instance with type-erase (basically it is a virtual function table, manually implemented) and write your usual traversal class to use the functions from table to control aligned_storage<?...> .
Now it can be done easier by using boost::variant or through something like my some type, which acts like any without using heap storage. Some link includes an implementation that compiles the above pseudo-virtual function table technique. I probably misused leveled storage incorrectly, so be careful.