from Hacker News

Show HN: Cppmatch – Rust-Like Pattern Matching and Error Handling for C++

by Rucadi on 3/16/25, 5:07 PM with 9 comments

I've created cppmatch, a lightweight, header-only C++ library that brings Rust-inspired pattern matching and error handling to C++.

It 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!

  • by nickysielicki on 3/17/25, 4:18 AM

    https://libfn.org/ also is worth a look.
  • by j1elo on 3/17/25, 1:20 AM

    This 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.

  • by senkora on 3/17/25, 2:12 AM

    Have you considered using the immediately invoked function expression (IIFE) pattern as a standards-compliant alternative to gcc statement expressions?
  • by bestouff on 3/16/25, 10:38 PM

    Please leave that Frankenstein of a language alone. Stop bolting features on it, it's already a monster.