#include#include int main() { boost::optional value; value = 10; std::cout << "Value is present: " << value.is_initialized() << std::endl; // Output: 1 std::cout << "Value is: " << value.get() << std::endl; // Output: 10 value.reset(); std::cout << "Value is present: " << value.is_initialized() << std::endl; // Output: 0 try { std::cout << "Value is: " << value.get() << std::endl; } catch (const boost::bad_optional_access& ex) { std::cerr << "Error: " << ex.what() << std::endl; // Output: "Error: attempting to get value of uninitialized optional" } return 0; }
#includeBoost.Optional is part of the Boost C++ Libraries package.#include void printValue(boost::optional value) { if (value) { std::cout << "Value is: " << value.get() << std::endl; } else { std::cerr << "Error: value is absent" << std::endl; } } int main() { boost::optional value; printValue(value); // Output: "Error: value is absent" value = 5; printValue(value); // Output: "Value is: 5" return 0; }