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