How do I use std::optional/variant/any in C++17?

Learn how to use std::optional, std::variant, and std::any in C++17. These features provide ways to handle optional values, multiple types, and any type of value, enhancing type safety and flexibility in your code.

C++, C++17, std::optional, std::variant, std::any, type safety, programming, examples

// Example of std::optional #include <optional> #include <iostream> std::optional getValue(bool returnValue) { if (returnValue) { return 42; } else { return std::nullopt; // No value } } int main() { auto value = getValue(true); if (value) { std::cout << "Value: " << *value << std::endl; } else { std::cout << "No value returned." << std::endl; } return 0; } // Example of std::variant #include <variant> #include <iostream> std::variant getVariant(bool returnString) { if (returnString) { return "Hello, World!"; } else { return 42; } } int main() { auto var = getVariant(false); std::visit([](auto&& arg){ std::cout << arg << std::endl; }, var); return 0; } // Example of std::any #include <any> #include <iostream> std::any getAnyValue() { return 3.14; // can store different types } int main() { auto value = getAnyValue(); try { std::cout << std::any_cast(value) << std::endl; // Cast to double } catch (const std::bad_any_cast& e) { std::cout << "Bad cast!" << std::endl; } return 0; }

C++ C++17 std::optional std::variant std::any type safety programming examples