Evaluate an expected-like expression into a structured binding.
Declared in <mrdocs/Support/Error/Expected.hpp>
#define MRDOCS_TRY_BIND(names, expr)
Works like the two-argument form of MRDOCS_TRY, but unpacks the value into a structured binding. The expression is evaluated once. If it failed, the enclosing function returns Unexpected with its error. Otherwise the value is moved into auto [names...]. The enclosing function must return an mrdocs::Expected. See MRDOCS_TRY for what counts as failed.
Wrap the binding names in parentheses, so the commas between them aren't taken as macro-argument separators:
Expected<std::pair<std::string, int>>
splitKeyValue(std::string_view line);
Expected<Option>
parseOption(std::string_view line)
{
MRDOCS_TRY_BIND((key, value), splitKeyValue(line));
return Option{std::move(key), value};
}
The body of parseOption expands to roughly this:
// Simplified: the hidden local is really named
// expected_result_<line>, and failed/error are
// ::mrdocs::detail::failed and ::mrdocs::detail::error.
// MRDOCS_TRY_BIND((key, value), splitKeyValue(line));
auto tmp = splitKeyValue(line);
if (failed(tmp)) {
return Unexpected(error(tmp));
}
auto [key, value] = *std::move(tmp);
return Option{std::move(key), value};
Any type that supports structured bindings works, with as many names as it has elements:
Expected<std::tuple<std::string, int, int>>
parseLocation(std::string_view text);
Expected<int>
lineOf(std::string_view text)
{
MRDOCS_TRY_BIND((file, line, column), parseLocation(text));
return line;
}
Things to keep in mind:
The binding is always auto [...]: you can't make it const or a reference. The names bind to a fresh object moved out of the result.
There's no custom-message form. If you need one, use MRDOCS_TRY(auto v, expr, msg) and bind v yourself.
Like MRDOCS_TRY, it expands to several statements, needs a trailing semicolon, can't appear twice on the same line, and needs braces when it's the body of an if, else, or loop.
| Name | Description |
|---|---|
| names | The parenthesized list of binding names. |
| expr | The expected-like expression to evaluate. |