#include <iostream>
#include <optional>
int main()
{
std::optional<int> optionalInt;
int Int ;
Int = optionalInt.value_or(-1);
std::cout << Int << " ";
std::cout << optionalInt.has_value() << " ";
try
{
Int = optionalInt.value();
}
catch(std::bad_optional_access e)
{
std::cout << "bad ";
}
std::cout << ": ";
optionalInt = std::optional<int>(3);
Int = optionalInt.value_or(-1);
std::cout << Int << " ";
std::cout << optionalInt.has_value() << " ";
try
{
Int = optionalInt.value();
}
catch(std::bad_optional_access e)
{
std::cout << "bad ";
}
std::cout << std::endl;
return 0;
}
// Output: -1 0 bad : 3 1
References:https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/utility/optional/value
No comments:
Post a Comment