std::any_cast - cppreference.com (original) (raw)
Performs type-safe access to the contained object.
Let U be std::remove_cv_t<std::remove_reference_t<T>>.
4,5) The program is ill-formed if std::is_void_v<T> is true.
[edit] Parameters
| operand | - | target any object |
|---|
[edit] Return value
1,2) Returns static_cast<T>(*std::any_cast<U>(&operand)).
- Returns static_cast<T>(std::move(*std::any_cast<U>(&operand))).
4,5) If operand is not a null pointer, and the
of the requested T matches that of the contents of operand, a pointer to the value contained by operand, otherwise a null pointer.
[edit] Exceptions
[edit] Example
#include #include #include #include #include int main() { // Simple example auto a1 = std::any(12); std::cout << "1) a1 is int: " << std::any_cast(a1) << '\n'; try { auto s = std::any_cast<std::string>(a1); // throws } catch (const std::bad_any_cast& e) { std::cout << "2) " << e.what() << '\n'; } // Pointer example if (int* i = std::any_cast(&a1)) std::cout << "3) a1 is int: " << *i << '\n'; else if (std::string* s = std::any_cast<std::string>(&a1)) std::cout << "3) a1 is std:🧵 " << *s << '\n'; else std::cout << "3) a1 is another type or unset\n"; // Advanced example a1 = std::string("hello"); auto& ra = std::any_cast<std::string&>(a1); // reference ra[1] = 'o'; std::cout << "4) a1 is string: " << std::any_cast<const std::string&>(a1) << '\n'; // const reference auto s1 = std::any_cast<std::string&&>(std::move(a1)); // rvalue reference // Note: “s1” is a move-constructed std:🧵 static_assert(std::is_same_v<decltype(s1), std::string>); // Note: the std::string in “a1” is left in valid but unspecified state std::cout << "5) a1.size(): " << std::any_cast<std::string>(&a1)->size() // pointer << '\n' << "6) s1: " << s1 << '\n'; }
Possible output:
- a1 is int: 12
- bad any_cast
- a1 is int: 12
- a1 is string: hollo
- a1.size(): 0
- s1: hollo
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3305 | C++17 | the behavior of overloads (4,5) was unclear if T is void | the program ill-formed in this case |