Skip to content

Any

Any

The class std::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. Implementations are encouraged to avoid dynamic allocations for small objects, but such an optimization may only be applied to types for which std::is_nothrow_move_constructible returns true.

1
2
// Be careful when using it
std::any a = 1;

1
std::cout << a.type().name() << ": " << std::any_cast<int>(a) << '\n';

1
2
a = 3.14;
std::cout << a.type().name() << ": " << std::any_cast<double>(a) << '\n';

1
2
a = true;
std::cout << a.type().name() << ": " << std::any_cast<bool>(a) << '\n';

1
2
a = std::string("Any string");
std::cout << a.type().name() << ": " << std::any_cast<std::string>(a) << '\n';

1
2
3
4
5
6
try {
    std::any v = 1;
    std::cout << std::any_cast<float>(v) << '\n';
} catch (std::bad_any_cast &e) {
    std::cout << e.what() << '\n';
}

1
2
3
4
5
std::any s2 = 1;
if (!s2.has_value()) {
    const std::type_info &ti = s2.type();
    std::cout << ti.name() << '\n';
}

1
2
3
std::any a3 = 1;
int *i = std::any_cast<int>(&a3);
std::cout << *i << '\n';

Share Snippets