Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active October 31, 2019 07:12
Show Gist options
  • Save wi7a1ian/f3180714e59c6c112c11ac8d4ccdfb6d to your computer and use it in GitHub Desktop.
Save wi7a1ian/f3180714e59c6c112c11ac8d4ccdfb6d to your computer and use it in GitHub Desktop.
Using std::expected in C++ #cpp #functional
auto parse_int(std::string_view str)
-> std::expected<int, std::domain_error>
{
int i;
std::stringstream ss;
ss << str;
ss >> i;
if(ss.fail())
return std::make_unexpected( std::domain_error("value is not an integer") );
return i;
}
auto result = parse_int( input );
if( result )
std::cout << *result << "\n";
else
std::cerr << "Error: " << result.error().what() << "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment