How do I avoid exceptions and handle errors std::any in C++?

In C++, std::any is a powerful type that can hold any value type. However, using std::any can lead to exceptions if you're not careful about the type you attempt to retrieve. To avoid exceptions while working with std::any, you can use the safe access functions such as std::any_cast with a check or a wrapper function that handles errors gracefully.

Example of Safe Access with std::any

#include #include #include void printAnyValue(const std::any& value) { if (value.type() == typeid(int)) { std::cout << std::any_cast(value) << std::endl; } else if (value.type() == typeid(std::string)) { std::cout << std::any_cast<:string>(value) << std::endl; } else { std::cout << "Unsupported type" << std::endl; } } int main() { std::any myValue = std::string("Hello, World!"); printAnyValue(myValue); myValue = 42; printAnyValue(myValue); // Demonstrating an unsupported type myValue = 3.14; printAnyValue(myValue); return 0; }

C++ std::any exception handling error management type safety