r/cpp • • Mar 10 '26

Deriving Type Erasure

https://david.alvarezrosa.com/posts/deriving-type-erasure/
59 Upvotes

34 comments sorted by

View all comments

Show parent comment

5

u/_Noreturn Mar 10 '26

I literally never used std::any and I still to this day can't figure out a usecasw for it

10

u/david-alvarez-rosa Mar 10 '26

Fair enough. This post is about how type erasure can be achieved, not proposing use cases for std::any

std::function uses type erasure and it's used by quite a bit of people

6

u/mjklaim Mar 10 '26

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.

2

u/Jcsq6 Mar 10 '26

Type safe user pointer is the only one I know of.

5

u/_Noreturn Mar 10 '26

In 99.9% of libraries I use the user pointer isn't owned it is referenced only

2

u/Business_Welcome_870 Mar 10 '26

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.

1

u/david-alvarez-rosa Mar 10 '26

Nice! Would you like to share the link?

1

u/LiAuTraver Mar 10 '26

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).

1

u/duneroadrunner Mar 11 '26

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.

1

u/Electronic_Tap_8052 Mar 11 '26

tree of nodes where each node can be anything, have any parent, and have any number of children. Godot uses it.