std:: optional and std::expected
C++17 introduced std::optional, a template class that either has a value or has nothing. This is useful for situations where a function may or may not return a value. To better understand it, let’s go through the following example:
#include <cstdio>
#include <optional>
struct sensor {
struct data {
int x;
int y;
};
static inline bool ret_val = true;
static std::optional<data> get_data() {
ret_val = !ret_val;
if(ret_val) {
return data{4, 5};
}
else {
return std::nullopt;
}
}
};
int main()
{
const auto get_data_from_main = [] () {
auto result = sensor::get_data();
if(result) {
printf("x = %d, y = %d\r\n", (*result).x, (*result).y);
}
else {
printf("No data!\r\n");
}
};
get_data_from_main();
get_data_from_main();
return 0...