Migration from boost::any

The lesson shows how transition from boost to std can make things more flexible for you.

Boost Any was introduced around the year 2001 (Version 1.23.0). Interestingly, the author of the boost library - Kevlin Henney - is also the author of the proposal for std::any. So the two types are strongly connected, and the STL version is heavily based on the predecessor.

Here are the main changes:

Feature Boost.Any (1.67.0) std::any
Extra memory allocation Yes Yes
Small buffer optimisation Yes Yes
emplace No Yes
in_place_type_t in constructor No Yes

There are not many differences between the two types. Most of the time you can easily convert from boost.any into the STL version.

Examples of std::any

The core of std::any is flexibility. In the below examples, you can see some ideas (or concrete implementations) where holding variable type can make an application a bit simpler.

Parsing files

In the examples for std::variant you can see how it’s possible to parse configuration files and store the result as an alternative of several types. If you write an entirely generic solution - for example as a part of some library, then you might not know all the possible types.

Storing std::any as a value for a property might be good enough from the performance point of view and will give you flexibility.

Message Passing

In Windows API, which is C mostly, there’s a message passing system that uses message ids with two optional parameters which store the value of the message. Based on that mechanism you can implement WndProc to handle the messages passed to your window/control:

Get hands-on with 1200+ tech skills courses.