| | 70 | |
| | 71 | == Any type == |
| | 72 | |
| | 73 | Hold a copy of a value and its type. |
| | 74 | |
| | 75 | {{{ |
| | 76 | #include <any> |
| | 77 | #include <iostream> |
| | 78 | #include <string> |
| | 79 | |
| | 80 | int main() { |
| | 81 | std::any a; // Empty std::any |
| | 82 | |
| | 83 | a = 42; // Stores an int |
| | 84 | std::cout << "Value: " << std::any_cast<int>(a) << std::endl; |
| | 85 | |
| | 86 | a = "Hello, C++!"; // Stores a const char* |
| | 87 | std::cout << "Value: " << std::any_cast<const char*>(a) << std::endl; |
| | 88 | |
| | 89 | a = std::string("Dynamic string"); // Stores a std::string |
| | 90 | std::cout << "Value: " << std::any_cast<std::string>(a) << std::endl; |
| | 91 | |
| | 92 | try { |
| | 93 | // Attempting to cast to the wrong type will throw an exception |
| | 94 | std::cout << std::any_cast<double>(a) << std::endl; |
| | 95 | } catch (const std::bad_any_cast& e) { |
| | 96 | std::cerr << "Error: " << e.what() << std::endl; |
| | 97 | } |
| | 98 | |
| | 99 | return 0; |
| | 100 | } |
| | 101 | }}} |