From 984346bd779c3dbfcdaec7f517d971c0afce365e Mon Sep 17 00:00:00 2001 From: Amar Mahmutbegovic Date: Thu, 4 Jul 2024 01:09:13 +0200 Subject: [PATCH] add std::optional example --- Chapter07/error_handling/CMakeLists.txt | 2 +- .../app/src/main_exceptions.cpp | 1 - .../error_handling/app/src/main_expected.cpp | 28 +++++++++ .../error_handling/app/src/main_optional.cpp | 58 +++++++++++++++++++ 4 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 Chapter07/error_handling/app/src/main_expected.cpp create mode 100644 Chapter07/error_handling/app/src/main_optional.cpp diff --git a/Chapter07/error_handling/CMakeLists.txt b/Chapter07/error_handling/CMakeLists.txt index 29cdd1e..dbf1b83 100644 --- a/Chapter07/error_handling/CMakeLists.txt +++ b/Chapter07/error_handling/CMakeLists.txt @@ -84,7 +84,7 @@ project(bare VERSION 1.0.6) enable_language(C CXX ASM) -set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED True) # global include directories diff --git a/Chapter07/error_handling/app/src/main_exceptions.cpp b/Chapter07/error_handling/app/src/main_exceptions.cpp index 7605d28..30a44f6 100644 --- a/Chapter07/error_handling/app/src/main_exceptions.cpp +++ b/Chapter07/error_handling/app/src/main_exceptions.cpp @@ -21,7 +21,6 @@ template struct ring_buffer { } }; - int main() { hal::init(); diff --git a/Chapter07/error_handling/app/src/main_expected.cpp b/Chapter07/error_handling/app/src/main_expected.cpp new file mode 100644 index 0000000..3d8dd34 --- /dev/null +++ b/Chapter07/error_handling/app/src/main_expected.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + + +#include + +#include +#include + +#include + +int main() +{ + hal::init(); + + hal::uart_stm32 uart(USART2); + uart.init(); + + retarget::set_stdio_uart(&uart); + + printf("std::expected example\r\n"); + + while(true) + { + } +} + \ No newline at end of file diff --git a/Chapter07/error_handling/app/src/main_optional.cpp b/Chapter07/error_handling/app/src/main_optional.cpp new file mode 100644 index 0000000..7d228ba --- /dev/null +++ b/Chapter07/error_handling/app/src/main_optional.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include + +#include + +#include +#include + +#include + +struct sensor { + struct data { + int x; + int y; + }; + static inline bool ret_val = true; + static std::optional get_data() { + ret_val = !ret_val; + if(ret_val) { + return data{4, 5}; + } + else { + return std::nullopt; + } + } +}; + +int main() +{ + hal::init(); + + hal::uart_stm32 uart(USART2); + uart.init(); + + retarget::set_stdio_uart(&uart); + + printf("std::optional example\r\n"); + + 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(); + + while(true) + { + } +} + \ No newline at end of file