|
147 | 147 | \end{exerciseWithShortcut} |
148 | 148 | \end{frame} |
149 | 149 |
|
| 150 | +\begin{frame}[fragile] |
| 151 | + \frametitlecpp[23]{std::expected \cpprefLink{https://en.cppreference.com/w/cpp/utility/expected}} |
| 152 | + \begin{block}{Manages either of 2 values (expected or not)} |
| 153 | + \begin{itemize} |
| 154 | + \item templated by the 2 value types |
| 155 | + \item Useful for the return value of a function that may fail |
| 156 | + \begin{itemize} |
| 157 | + \item and would then return another type (error type) |
| 158 | + \end{itemize} |
| 159 | + \end{itemize} |
| 160 | + \end{block} |
| 161 | + \begin{exampleblock}{} |
| 162 | + \small |
| 163 | + \begin{cppcode*}{} |
| 164 | + enum class Error {...}; |
| 165 | + std::expected<int, Error> parse(std::string_view in) { |
| 166 | + if (is_valid(in)) return convert_to_int(in); |
| 167 | + return std::unexpected(Error::...); |
| 168 | + } |
| 169 | + auto v = parse(...); |
| 170 | + if (v.has_value()) { |
| 171 | + std::cout << *v; // (unchecked) |
| 172 | + foo(v.value()); // may throw bad_expected_access |
| 173 | + } else |
| 174 | + log(v.error()); |
| 175 | + \end{cppcode*} |
| 176 | + \end{exampleblock} |
| 177 | +\end{frame} |
| 178 | + |
150 | 179 | \begin{frame}[fragile] |
151 | 180 | \frametitlecpp[17]{std::variant \cpprefLink{https://en.cppreference.com/w/cpp/utility/variant}} |
152 | 181 | \begin{block}{A type-safe union} |
|
0 commit comments