std::any - cppreference.com (original) (raw)

| Defined in header | | | | ------------------------------------------------------------- | | ------------- | | class any; | | (since C++17) |

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. The stored instance is called the contained object. Two states are equivalent if they are either both empty or if both are not empty and if the contained objects are equivalent.

  2. The non-member any_cast functions provide type-safe access to the contained object.

Typically, implementations apply small objects optimization (avoid dynamic allocations) to types for which std::is_nothrow_move_constructible is true.

Contents

[edit] Member functions

(constructor) constructs an any object (public member function) [edit]
operator= assigns an any object (public member function) [edit]
(destructor) destroys an any object (public member function) [edit]
Modifiers
emplace change the contained object, constructing the new object directly (public member function) [edit]
reset destroys contained object (public member function) [edit]
swap swaps two any objects (public member function) [edit]
Observers
has_value checks if object holds a value (public member function) [edit]
type returns the typeid of the contained value (public member function) [edit]

[edit] Non-member functions

[edit] Helper classes

| | exception thrown by the value-returning forms of any_cast on a type mismatch (class) [edit] | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

[edit] Notes

Feature-test macro Value Std Feature
__cpp_lib_any 201606L (C++17) std::any

[edit] Example

Possible output:

int: 1 double: 3.14 bool: true bad any_cast int: 2 no value 3

[edit] See also

function(C++11) copyable wrapper of any copy constructible callable object (class template) [edit]
move_only_function(C++23) move-only wrapper of any callable object that supports qualifiers in a given call signature (class template) [edit]
variant(C++17) a type-safe discriminated union (class template) [edit]
optional(C++17) a wrapper that may or may not hold an object (class template) [edit]
unique_ptr(C++11) smart pointer with unique object ownership semantics (class template) [edit]
indirect(C++26) a wrapper containing dynamically-allocated object with value-like semantics (class template) [edit]
polymorphic(C++26) a polymorphic wrapper containing dynamically-allocated object with value-like semantics (class template) [edit]