So, we have
Foo parseFoo(std::string_view input);
What if the parse fails? And you can't parse out a Foo?
- throw an exception
- return default Foo. ie
Foo()
(if Foo is default constructible) bool parseFoo(std::string_view input, Foo & output);
// also basically requiresFoo()
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.