Skip to content

Latest commit

 

History

History
106 lines (74 loc) · 1.5 KB

optional.md

File metadata and controls

106 lines (74 loc) · 1.5 KB

std::optional<T>

So, we have

Foo parseFoo(std::string_view input);

What if the parse fails? And you can't parse out a Foo?

  1. throw an exception
  2. return default Foo. ie Foo() (if Foo is default constructible)
  3. bool parseFoo(std::string_view input, Foo & output); // also basically requires Foo()
  4. Foo * parseFoo(std::string_view input); // allocation!? :-(
C++14 C++17
// returns default Foo on error
Foo parseFoo(std::string_view in);

// throws parse_error
Foo parseFoo(std::string_view in);

// returns false on error
bool parseFoo(std::string_view in, Foo & output);

// returns null on error
unique_ptr<Foo> parseFoo(std::string_view in);



std::optional<Foo> parseFoo(std::string_view in);

Usage

C++17
optional ofoo = parseFoo(str);
if (ofoo)
   use(*ofoo);
// nicer with new if syntax:
if (optional ofoo = parseFoo(str); ofoo)
   use(*ofoo);
optional<int> oi = parseInt(str);
std::cout << oi.value_or(0);

Note, optional is not just for errors, and exceptions are still the go-to choice for error handling.
See also boost::optional, Haskell's Maybe, etc.