Ever looked at std::any and wondered what's going on behind the scenes? Beneath the intimidating interface is a classic technique called type erasure: concrete types hidden behind a small, uniform wrapper.
Starting from familiar tools like virtual functions and templates, we'll build a minimal std::any. By the end, you'll have a clear understanding of how type erasure works under the hood.
So, the approach used by libc++ is to store a pointer to a function that dispatches operations based on its parameters, while the traditional virtual-function approach is to store a pointer to a table of function pointers, which compilers dispatch to using a statically determined offset. These two approaches seem quite similar to me. What is the significant difference between them?
Type erasing using a polymorphic type as base would mean that you're using an extra 8 bytes of space. For example, MSVC's std::any is 64 bytes in size, 8 bytes for a pointer, 56 bytes for small buffer optimization. If you use a polymorphic type, you effectively only have 48 bytes of SBO because 8 bytes are being taken by the vtable pointer.
The other difference, with libc++'s version there's 1 less level of indirection. Using a polymorphic base would be
Inside that function, it still redirects. Due to inlining, that might be less impactful. Due to code ordering, that could also be close together in the exe even if not inlined.
Another interesting difference is that you don't need vtables. Not just the 8 bytes are relevant here, though also the separate space where the table gets stored is no longer needed. It might sound less relevant, though it's an optimization towards the size of the executable. Especially relevant if you store many different types in it.
Assuming the typeid does not get inlined, it also would allow for COMDAT folding/ICF. (Common data folding?/Identical code folding?) That again would reduce the size of the executable.
A side effect of the size reductions above is that you also have a higher chance of getting a cache hit for the code to be executed.
It's all small stuff, though it might make a noticeable impact on performance when used at scale.
In the above, the _RTTI member is a pointer to a hand-rolled virtual table, and the _TypeData member is a tagged pointer (encoding whether SBO is in effect) to a type_info object. If the virtual-function approach were chosen, the _RTTI member could be eliminated, so the available SBO space would actually be the same in both approaches. So I think what matters more is the extra indirection involved in the virtual-function approach, as you mentioned.
Typical usage I have seen and used it so far is when you provide a system (as a library) but allow the user-code of the system to "attach" data, arbitrary values, to parts of that system, for their own convenience, withouth that system touching that data. For example a non-generic library presenting as a kind of graph and allowing arbitrary data to be attached to some kinds of nodes in the graph. It's not like you'll use it everyday, but it's useful as a customization point (like any type-erasing types, I guess?).
It's also used sometimes as implementation detail of type-erasing types, because usually std::any is implemented in a way that benefits from small-buffer-optimization (SBO), although it's kind of limited for that usage.
Someone made a post in another sub about creating a tuple that the user didn't have to specify the template arguments for. CTAD wouldn't cut it. So he created a new class and wrapped a tuple around it in an any. Template tricks were used to convert the any back to the correct type when the user wanted.
ANTLR runtime uses any as visitor(recognizer, in a more abstract way) return types, which in my view is a trade off between code reusability and code performance. The counter example is to use a big variant and CRTP , where it's inheritance won't be possible.
Argparse uses std any as internal storage of actual argument.
This is the only use case I thought using std any makes sense; also both library ain't native c++ but ported from other language (java and python).
I found it useful in the auto-translation of C code to a memory-safe subset of C++. The translation involves replacing void * pointers with a compatible type-safe replacement. In general, in order to check that casts from the void * replacement are type-safe, you need to preserve and store (at run-time) the type of the original source pointer associated with the value of the void * replacement.
You lose the ability for SBO, but apart from that it's virtually (pun intended) identical to the more sophisticated version of type erasure based on function pointers...
15
u/david-alvarez-rosa Mar 10 '26
Ever looked at std::any and wondered what's going on behind the scenes? Beneath the intimidating interface is a classic technique called type erasure: concrete types hidden behind a small, uniform wrapper.
Starting from familiar tools like virtual functions and templates, we'll build a minimal std::any. By the end, you'll have a clear understanding of how type erasure works under the hood.
5
u/Business_Welcome_870 Mar 10 '26
What font is that? Looks nice
2
u/david-alvarez-rosa Mar 10 '26
Also cross-posted in Hacker News if lads like there more https://news.ycombinator.com/item?id=47321469
2
u/anotherprogrammer25 Mar 11 '26
Thanks for the article. Really good explanation.
2
u/jonathanhiggs Mar 10 '26
Isn’t this the worst form of type erasure? It wraps the object but also uses polymorphism
1
u/Rare-Instance7961 Mar 13 '26
nit: "consoomer"
Great article