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.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?