C++17 introduces the object container std::any
, based on the boost library boost::any
.
My question is: Is the standardized any
equivalent to the boost version, or are there differences?
A similar question has been posted about variant
, and some differences exist in that case, but I could not find references about any
.
EDIT: A difference I could see is the availability of the methods emplace
. More than a difference in the API I'm interested to the differences between the behavior and the guarantees. For instance, different allocations would be significant for me.
The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type.
The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.
std::any uses Small Buffer Optimization, so it will not dynamically allocate memory for simple types like ints, doubles… but for larger types it will use extra new . std::any might be considered 'heavy', but offers a lot of flexibility and type-safety.
Boost. Variant, part of collection of the Boost C++ Libraries. It is a safe, generic, stack-based discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner.
I'm interested to the differences between the behavior and the guarantees.
There aren't any behavioral differences; not really. They both have the same requirements on the ValueType (copy-constructible, and a destructor that doesn't emit exceptions). They both provide the same operations on the values they store, with pretty much identical exception guarantees.
The principle difference is that boost::any
's implementation at present doesn't implement small object optimization, while std::any
implementations may provide it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With