Show HN: Cppmatch – Rust-Like Pattern Matching and Error Handling for C++
42 points by Rucadi 3 months ago | 9 commentsIt tries to imitate the functionality of the questionmark (?) operator in C++ by using a macro that uses the gcc extension https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
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.
The ? operator translates to *expect* To 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)
You can view an example of this project used in a "real way" in compiler-explorer:
Simplified error types to just be a string: https://compiler-explorer.com/z/6j3866E7W
Multiple structs as error types: https://compiler-explorer.com/z/encbf5f43
Feel free to give feedback or contribute to the project!
- nickysielicki 3 months agohttps://libfn.org/ also is worth a look.
- exradr 3 months agoAt a glance, looks good, but it really needs some better documentation! It doesn't seem to include anything similar to this project's expect macro though.
- exradr 3 months ago
- j1elo 3 months agoThis is great! Thanks for sharing, it is a cool idea to try bringing QoL improvements from Rust to C++. Got a question:
Does this prevent the RVO/NRVO compiler optimizations for return values? And when those fail, same question for the move-construction for types that do have a move constructor.
- Rucadi 3 months agoRVO/NRVO are valid and are not affected.
We are dealing with std::variant, and the move semantics are defined by the alternative. https://en.cppreference.com/w/cpp/utility/variant/operator%3...
- Rucadi 3 months ago
- senkora 3 months agoHave you considered using the immediately invoked function expression (IIFE) pattern as a standards-compliant alternative to gcc statement expressions?
- Rucadi 3 months agoThe main problem with IIFE is the same as with a normal function:
You cannot return the caller function from inside the closure, making the "short-circuit" mechanism provided by questionmark (?) operator not possible.
With the GCC Extension, we get around that using a construct that is pretty similar to IIFE, it allows to return a value from an immediate expression created by a block of code that is surrounded by ({})
The nice thing about this block ({}) is that the last statement is used as the "return value" without an explicit return, this disambiguates between the "expression" return and the "function" return.
Without compiler support, the short-circit is not possible, but with this feature + macros we can create a function that behaves like that.
- Rucadi 3 months ago
- Wumpnot 3 months ago[flagged]
- bestouff 3 months agoPlease leave that Frankenstein of a language alone. Stop bolting features on it, it's already a monster.