template<class T> T any_cast(const any& operand); | (1) | (since C++17) |
template<class T> T any_cast(any& operand); | (2) | (since C++17) |
template<class T> T any_cast(any&& operand); | (3) | (since C++17) |
template<class T> const T* any_cast(const any* operand) noexcept; | (4) | (since C++17) |
template<class T> T* 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<T>>
.
operand | - | target any object |
static_cast<T>(*std::any_cast<U>(&operand))
static_cast<T>(std::move(*std::any_cast<U>(&operand)))
.operand
is not a null pointer, and the typeid
of the requested T
matches that of the contents of operand
, a pointer to the value contained by operand, otherwise a null pointer.std::bad_any_cast
if the typeid
of the requested T
does not match that of the contents of operand
.#include <string> #include <iostream> #include <any> #include <utility> 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&&>(std::move(a)); //< rvalue reference // Note: 'b' is a move-constructed std::string, // 'a' is left in valid but unspecified state std::cout << "a: " << *std::any_cast<std::string>(&a) //< pointer << "b: " << b << '\n'; }
Possible output:
12 bad any_cast a: hollo a: b: hollo
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/utility/any/any_cast