Namespaces
Variants
Views
Actions

std::any_cast

From cppreference.com
< cpp‎ | utility‎ | any
template<class ValueType>
    ValueType any_cast(const any& operand);
(1) (since C++17)
template<class ValueType>
    ValueType any_cast(any& operand);
(2) (since C++17)
template<class ValueType>
    ValueType any_cast(any&& operand);
(3) (since C++17)
template<class ValueType>
    const ValueType* any_cast(const any* operand) noexcept;
(4) (since C++17)
template<class ValueType>
    ValueType* any_cast(any* operand) noexcept;
(5) (since C++17)

Performs type-safe access to the contained object.

Let U be std::remove_cv_t<std::remove_reference_t<ValueType>>.

1) The program is ill-formed if is_constructible_v<ValueType, const U&> is not true.
2) The program is ill-formed if is_constructible_v<ValueType, U&> is not true.
3) The program is ill-formed if is_constructible_v<ValueType, U> is not true.

Contents

[edit] Parameters

operand - target any object

[edit] Return value

1-2) Returns static_cast<ValueType>(*std::any_cast<U>(&operand))
3) Returns static_cast<ValueType>(std::move(*std::any_cast<U>(&operand))).
4-5) If operand is not a null pointer, and the typeid of the requested ValueType matches that of the contents of operand, a pointer to the value contained by operand, otherwise a null pointer.

[edit] Exceptions

1-3) Throws std::bad_any_cast if the typeid of the requested ValueType does not match that of the contents of operand.

[edit] Example

#include <string>
#include <iostream>
#include <any>
 
int main()
{
    // simple example 
 
    auto a = std::any(12);
 
    std::cout << std::any_cast<int>(a) << '\n'; 
 
    try {
        std::cout << std::any_cast<std::string>(a) << '\n';
    }
    catch(const std::bad_any_cast& e) {
        std::cout << e.what() << '\n';
    }
 
    // advanced example
 
    a = std::string("hello");
 
    auto& ra = std::any_cast<std::string&>(a); //< reference
    ra[1] = 'o';
 
    std::cout << "a: " << std::any_cast<const std::string&>(a) << '\n'; //< const reference
 
    auto b = std::any_cast<std::string&&>(a); //< rvalue reference (no need for std::move)
 
    // Note, 'b' is a move-constructed std::string, 'a' is now empty
 
    std::cout << "a: " << *std::any_cast<std::string>(&a) //< pointer
        << "b: " << b << '\n';
}

Output:

12
bad any_cast
a: hollo
a: b: hollo