{"by":"Rucadi","descendants":9,"id":43380487,"kids":[43385172,43384261,43384555,43383880,43383215],"score":42,"text":"I&#x27;ve created cppmatch, a lightweight, header-only C++ library that brings Rust-inspired pattern matching and error handling to C++.<p>It tries to imitate the functionality of the questionmark (?) operator in C++ by using a macro that uses\nthe gcc extension <a href=\"https:&#x2F;&#x2F;gcc.gnu.org&#x2F;onlinedocs&#x2F;gcc&#x2F;Statement-Exprs.html\" rel=\"nofollow\">https:&#x2F;&#x2F;gcc.gnu.org&#x2F;onlinedocs&#x2F;gcc&#x2F;Statement-Exprs.html</a><p>This allows to create exceptionless code with non-intrusive error-as-value that unlike Exceptions, makes it clear which kinds of error a function can generate and forces you to handle (or ignore) them.<p>The ? operator translates to *expect*\nTo handle the errors I introduce *match* which allows to easily visit the contents of the result or any std::variant (you can use it to imitate rust enums)<p>You can view an example of this project used in a &quot;real way&quot; in compiler-explorer:<p>Simplified error types to just be a string: <a href=\"https:&#x2F;&#x2F;compiler-explorer.com&#x2F;z&#x2F;6j3866E7W\" rel=\"nofollow\">https:&#x2F;&#x2F;compiler-explorer.com&#x2F;z&#x2F;6j3866E7W</a><p>Multiple structs as error types: <a href=\"https:&#x2F;&#x2F;compiler-explorer.com&#x2F;z&#x2F;encbf5f43\" rel=\"nofollow\">https:&#x2F;&#x2F;compiler-explorer.com&#x2F;z&#x2F;encbf5f43</a><p>Feel free to give feedback or contribute to the project!","time":1742144823,"title":"Show HN: Cppmatch – Rust-Like Pattern Matching and Error Handling for C++","type":"story","url":"https://github.com/Rucadi/cpp-match"}