r/cpp • u/BarryRevzin • 2d ago
Pattern Matching for C++29
https://mpark.github.io/programming/2026/11/30/pattern-matching-for-cpp29/78
u/baudvine 2d ago
I'm really happy to see they're a) not a library feature, and b) expressions. This will unfuck so much of my code (in 10 years or so, lolsob)
40
u/mcypark 2d ago
a) not a library feature
Yep! I built a library first mpark/patterns in part to demonstrate justification for it needing to be a language feature. Gave a talk on it at CppCon 2017: https://www.youtube.com/watch?v=HaZ1UQXnuC8 (yikes, that was a long time ago π ).
b) expressions
Both statements and expressions are being proposed. The expression form is very nice indeed, but I realized while trying out the feature in practice that the statement form is actually plenty useful still.
20
u/martinus int main(){[]()[[]]{{}}();} 2d ago edited 2d ago
For match (dice_roll(), dice_roll()), is the call order defined? E.g. when using it with a rng like so:
match (dice_roll(rng), dice_roll(rng))where each call modifies the state of rng I'd very much want this to be deterministic and not depend on the compiler.
8
u/mcypark 1d ago
Hm... at the moment it's defined to have the same semantics as arguments to a function call, i.e. unspecified, without interleaving. It's an interesting point. Will have to think further about that π€
7
u/friedkeenan 1d ago
Clearly we ought to have another syntax of
match {dice_roll(rng), dice_roll(rng)}in order to get the intuitive evaluation order :P6
u/martinus int main(){[]()[[]]{{}}();} 1d ago
Oh wow I didn't know the order is defined inside a brace-init-list, so your example would actually makes total sense :)
40
u/steveklabnik1 2d ago
This looks great! Was pretty surprised to see examples I wrote for the Rust book suddenly appear on the page. They're a little contrived, but I think that makes them decent enough for initial examples here too.
Pattern matching is one of those features that, once you have it, you can't live without, in my experience.
20
u/mcypark 2d ago
Was pretty surprised to see examples I wrote for the Rust book suddenly appear on the page.
They're also in the paper P2688R6 π
Pattern matching is one of those features that, once you have it, you can't live without, in my experience.
I agree. Hopefully folks will get their hands on the implementation to play around with.
P.S. I remember you came to give a Rust talk at a start-up called Mesosphere where I was working, back in like... 2016 maybe? Anyway, that was pretty cool π
8
u/steveklabnik1 1d ago
They're also in the paper P2688R6 π
:D that's great. Just kind of funny, you know, when Carol and I came up with those, the idea that they'd eventually be used in other contexts was very far from our minds.
I remember you came to give a Rust talk at a start-up called Mesosphere where I was working, back in like... 2016 maybe?
I remember that too! Long long time ago. I just looked it up, it was July 2015, so that was two months after Rust 1.0. Glad you liked it. :)
6
u/atariPunk 1d ago
Thanks for your work. This looks great.
From the post it seems that there are two branches https://github.com/mpark/llvm-project/tree/p2688-pattern-matching and https://github.com/mpark/llvm-project/tree/p2688-selfhost
Which branch is the best to try this locally?
I have a project that uses a lot of std::variant and std::visitor that I would like to give this a try on.
10
u/caroIine 2d ago
After playing around with it on Compiler Explorer, I think it's a fantastic addition to C++
9
8
u/fdwr fdwr@github π 2d ago edited 2d ago
Love the consistent ordering of match (foo) {} like switch (foo) {}, versus the previously inconsistent foo match {}. Yay for cleaner code.
Patterns can also be combined with
or.
Is that a new contextual keyword?
Does it adversely interact with iso646.h? Never mind: "The punctuator || has the same grammatical meaning as the alternative token or"
case 1 or 2
Does that also play nicely with case ranges 1 ... 3 proposed here by u/eisenwave, like C case ranges? I see ... mentioned for pack expansion, but not case ranges.
5
u/mcypark 2d ago
Love the consistent ordering of match (foo) {} like switch (foo) {}, versus the previously inconsistent foo match {}. Yay for cleaner code.
No upside-down smile this time? π You've been very consistent about this over time, I'm glad you're happy.
Never mind: "The punctuator || has the same grammatical meaning as the alternative token or"
π
Does that also play nicely with case ranges [...]
Yeah, it should! I was hoping u/eisenwave would get to present P4040 in Buzios but unfortunately the scheduling got all messed up π. I think it makes a lot of sense to add it as a pattern once it's accepted. Depending on the timing, it might also make more sense for it to be a subsequent paper rather than being part of this initial effort, since the scope of this proposal is already quite large.
7
u/fdwr fdwr@github π 2d ago edited 2d ago
You've been very consistent about this over time...
I tend to be! π Here, accept another π, and I agree with you that the current proposal looks/feels much more natural C++, and I'm glad it's the most satisfied you've been with the feature so far π€.
Yeah, it should!
βοΈ
3
u/_bstaletic 21h ago
I'm joining those who voiced their satisfaction with the proposed syntax.
I found a minor bug. std::alternative_traits is not exported from the std module. https://godbolt.org/z/qbqxnKE7n
In short, there are two changes compared to your godbolt link:
All includes are replaced with
import std;and#include <cassert>-fmodules-driverpassed to the compiler.
5
8
u/fortsnek274 2d ago
And one of the irritants is that when I do something like that:
if (const auto *FD = dyn_cast<FunctionDecl>(D))
use(FD);
else if (const auto *VD = dyn_cast<VarDecl>(D))
use(VD);The variables have to have a different name as they stay in scope.
7
u/Lahvuun 2d ago edited 2d ago
Of course this has long been solved by C++17's if statement with initializer:
if (const auto *FOO = dyn_cast<FunctionDecl>(D); FOO) use(FOO); else if (const auto *FOO = dyn_cast<VarDecl>(D); FOO) use(FOO);edit: that is wrong, need to instead use separate if statements:
if (const auto *FOO = dyn_cast<FunctionDecl>(D); FOO) use(FOO); if (const auto *FOO = dyn_cast<VarDecl>(D); FOO) use(FOO);2
2
u/SirClueless 2d ago
Pretty sure this is the exact same, and will fail if using
-Wshadow -Werror: https://godbolt.org/z/Tjj4Y9Gd42
u/crowbarous 2d ago
The variables are in nested scopes, so they will shadow one another successfully. Your code as presented is OK if both variables were called, say, DD. A more unfortunate problem is that neither can be called D.
4
u/Miserable_Guess_1266 2d ago
Really hope we get this for C++29, looks super nice!
I've got a question about the index-based Illustrative Lowering in the paper. In the code, the switch-case indices are hard coded as 0 and 1. At first glance that looks like they just use the indices in order. But if I write something like:
match (std::expected<int, float>{123}) {
case { float error } => foo(); // try to match the error (index 1)...
case { int value } => bar(); // ... before the success (index 0)
}Would it not need to generate a switch with case 1 first, then case 0? Am I right to think the case indices must be determined by examining the type reflection in alternative_traits<...>::alternatives, and checking which "inner" projection they have a chance of matching, `float error` or `int value`?
4
u/mcypark 2d ago
Really hope we get this for C++29, looks super nice!
Thanks! I hope so too.
Would it not need to generate a switch with case 1 first, then case 0?
Right, that's essentially correct. It looks at
alternative_traits<...>::alternativesto determine the projectable states, and computes the type/value category ofget<Idx>(subject)for each projectable state. TheIdxs for whichget<Idx>(subject)matches thefloat errorare used in the lowering of theswitchcase, same forint value.
8
u/sweetno 2d ago
Why not first-class sum types?
14
u/mcypark 2d ago edited 2d ago
We should totally have them! Personally, I don't have the time to pursue it on top of pattern matching.
However, I will say that the named selectors part of alternative pattern is designed with a potential future first-class sum type in mind.
For example, if in the future we get something like:
// imaginary first-class sum type enum union Key { int id; std::string name; std::string alias; };then we could match that with named selectors like:
void f(const Key& key) { match (key) { case { .id: int id } => ; case { .name: const auto& name } => ; case { .alias: const auto& alias } => ; } }
2
u/martinus int main(){[]()[[]]{{}}();} 1d ago
I think there is a problem in the paper when a guard modifies the subject. From section 12.3:
If a guard modifies the subject, a later projection can be reused or recomputed.
Here is an example:
#include <cstdio>
#include <string>
#include <variant>
int main() {
std::variant<int, std::string> v = std::string("hello");
match(v) {
case { const std::string& s } if (v = 1; false) => ;
case { const std::string& s } => std::printf("string case, size %zu\n", s.size());
case { int i } => std::printf("int case, i = %d\n", i);
}
}The first case matches, then the guard assigns an int but fails. After that the variant holds an int, so I'd say the case { int i } should match. But the prototype gives this instead: https://godbolt.org/z/bx4zqfqjz
and prints
string case, size 140733546207224The prototype reuses the saved index but that reads invalid data. As far as I can say there are two ways to fix this: either forbid modifying the subject while matching, or the discriminator has to be reread after a guard has run.
OCaml had the same bug once: https://github.com/ocaml/ocaml/issues/7241
Disclaimer: I found this with the help of AI while reading the paper.
2
u/mcypark 1d ago
Right, this is one of the things that need to be fully settled still. What other languages generally do is to leave this unspecified, so if you modify the subject in a guard, you're on your own.
We could make it such that a guard essentially introduces a barrier of sorts, and the subsequent patterns may need to evaluate the subject and such, but that could get in the way of optimizations π€ I think whether I'm open to this would be dependent on use cases why modifying the subject in the middle of a match is actually useful. It certainly doesn't seem like something we should go out of the way to support, giving up optimization opportunities.
As far as forbidding modifying the subject in the guard, not sure exactly what that would mean. If it means undefined behavior to modify the subject, it seems somewhat worse than unspecified behavior here. If it means like, make it a compile-time error to mutate stuff in there, well. we could do constification like in Contracts but it doesn't really solve the problem since you can still modify stuff with constification.
Anyway, it's not a bug per se at the moment as much as, more work needed to nail down the semantics.
2
u/martinus int main(){[]()[[]]{{}}();} 1d ago
I agree, I wouldn't want to give up optimization for this. I don't really have a use case for modifying the subject, but I think it is something that could easily happen by accident. E.g. a state machine with
match (state)and a guard that calls member functions which modify the state. I found that Rust eventually had to forbid this too, and it had to break existing code for this: https://github.com/rust-lang/rust/pull/15989I think it's not really unspecified at the moment. When the index is reused the unchecked
getruns with the wrong index, and this is already UB.How about defining it like this though: "the subject must not change during a match". Then keep the cached index. A normal build just works like before and doesn't check this, so it's fast. And for a hardened build there could be a check if the saved index equals the new index, somewhat similar to the out of bounds check for indexing into an
std::vectorhttps://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3471r4.html#hardened-preconditions1
u/Nobody_1707 1d ago
I would have expected the match to be finished after that first match. The fact that it even tries the other cases seems like a bug.
1
u/mcypark 1d ago
The first match has a guard that fails, so it's correct to continue
2
u/Nobody_1707 1d ago
Oh, I see. That's what the
, falseis for. Yeah, that's a disgusting edge case. I think the proper fix is to disallow mutating the matched variable until after the match arm has been selected, but I imagine the committee is likely to waffle on it for a while.1
u/Volodya_Soldatenkov 1d ago
Mutability is so terrible. You take a good idea from a language that doesn't have it, you try to insert it into one that has it, you get infinite problems.
1
u/LiAuTraver 1d ago
Value category, move/copy would be a big issue here, the article didn't mention it.
1
u/shailist 10h ago
Great work!
Got a question regarding return statements inside match cases. I could not find any mention of that in the paper or the blog post.
Having return statements possible inside cases could enable matching std::expected, returning the error or evaluating to the result:
std::expected<int, Status> foo();
int bar = match (foo()) {
case { .value: auto&& result } => std::move(result);
case { .error: auto&& error } => return std::unexpected(std::move(error));
}If possible, this can also easily be abstracted into a macro:
#define CHECK(...) match ((__VA_ARGS__)) { \
case { .value: auto&& result } => std::move(result); \
case { .error: auto&& error } => return std::unexpected(std::move(error)); \
}
int result = CHECK(foo());Note: I know about starement expressions, but they aren't standardized.
1
u/Olipro 2d ago
Maybe it's just coincidence but this looks a heck of a lot like pattern matching in C#
And that suits me fine. Just surprised it didn't get a mention.
7
u/mcypark 1d ago edited 16h ago
It's not a coincidence. I took inspiration from tons of languages, C# certainly one of them. The proposal has elements from Rust, C#, Java, Python, Scala, Swift, and many others. I don't think it's necessarily more C# than other languages, but I guess I could've just mentioned all of them.
-8
u/Adequat91 2d ago
C++ looks less and less like C++. Probably, I'm getting too old.
13
15
-9
u/fortsnek274 2d ago
But we have consensus!
This is, of course, overwhelming support. It is also perfectly aligned with the overwhelming feedback Iβve received so far, which mainly consists of βthis feels like C++β and βthis is a significant improvementβ.
10
u/mcypark 2d ago edited 2d ago
Not quite sure what's being implied here, but I'm certainly not chasing some "barely consensus" that will "get the feature through".
While R5 did not gain consensus
20/11/6/13/5, there were a decent amount of "against" votes that were along the lines of "it's too late in the cycle" and "CWG is backed up having to review Reflection and probably Contracts soon". It seemed to me like just coming back with the R5 design targeted for C++29 might actually just "gain consensus". I had to really wrestle with myself whether what I thought were improvements in R6 would actually be worth it.Anyway, the point is, I'm absolutely more invested in and focused on delivering a great feature.
-7
u/crowbarous 2d ago edited 2d ago
Cases remain source-ordered. Overload ranking defines the conversions admitted by declaration matching; it does not reorder cases as an overload set would.
...
declarations use source-ordered first-match semantics rather than forming an overload set
...
This gives us the useful instantiation behavior of an overloaded visitor without turning the cases into an overload set.
As long as this is the case, this pattern matching is anti-C++ and must be kept away from C++. It focuses on 1% of simple cases and ignores why the visitor pattern (in C++) is so much more powerful than "pattern matching" in other languages: it uses C++'s mechanism for static polymorphism, overload resolution.
auto to_double1(auto x) {
return visit([](double x){ return x; }, x);
}
auto to_double2(auto x) {
return match(x){ case{double x} => x; };
}
int main() {
std::variant<short, int, long, double> x;
to_double1(x);
to_double2(x); // fail: "not exhaustive"
}...
overload classify1 = {
[](auto) { puts("catch-all"); },
[](floating_point auto) { puts("floating point"); },
[](integral auto) { puts("integral"); },
[](int) { puts("int"); },
};
void classify2(auto x) {
match(x) {
case auto => puts("catch-all");
case floating_point auto => puts("floating point");
case integral auto => puts("integral");
case int => puts("int");
};
}
int main() {
classify1(0); classify1(0.); classify1("0");
// ^^^ works correctly
classify2(0); classify2(0.); classify2("0");
// ^^^ everybody goes to catch-all?
// now I have to do the compiler's job and reorder my cases?
// what if there's no best ordering?
}I'm hoping that those 33 SF and zero SA for "more work in direction" mean for fixing this, rather than for getting it in. Otherwise what are we even doing...
4
u/BarryRevzin 1d ago
Otherwise what are we even doing...
What we are doing is providing an incredible tool, that solves your problem just fine.
The conversion to double example just needs a pattern that actually matches all the arms. With
std::visityou implicitly converted todoubleon the way into the visitor, here we need to do it on the way out (or explicitly yielddouble(x)or something):auto to_double2(std::variant<short, int, long, double> v) { return match (v) -> double { case { auto x } => x; }; }And the classifier just needs to recognize that we're doing first-match, not best-match. For some reason you've called this the compiler's job to reorder your cases, but it's actually your job to figure out what you actually want to do β which for stuff like this is easier to reason about first-match over best-match anyway:
void classify2(auto x) { match(x) { case int => puts("int"); case floating_point auto => puts("floating point"); case integral auto => puts("integral"); case _ => puts("catch-all"); }; }This is very straightforward: if it's an
int,"int". Otherwise, if it'sfloating_point,"floating point". Otherwise, if it'sintegral,"integral". Otherwise,"catch-all". There is no such straightforward reading of the best-match approach. And it's likewise easy to rearrange or add new arms when needed.-2
u/crowbarous 1d ago
I know exactly how to "fix" my examples so they begin behaving as "expected". I wrote them the way I wrote them deliberately, to compactly highlight the failings.
I'm sorry, but being told in the face of that that my problem is solved "just fine" by this "incredible tool" is difficult to interpret as much other than upbeat salesmanship. That's out of place.
4
u/BarryRevzin 1d ago
I don't know what failings you think you're highlighting, other than being unnecessarily combative.
In both your examples, pattern matching as proposed can easily solve both problems in no more code than your original solution. All I had to do was change spelling in the first example and move the catch-all to the bottom in the second. Which is, arguably, the right place for the catch-all to go.
Personally, I would never even use
overloadas the solution for that second example today (or really any example), precisely because it is very difficult to reason about overload resolution ordering. We usually talk about things in a linear priority order, which isn't overload resolution, it's first match.6
u/foonathan 2d ago
Ordered matches are far superior than overload resolution. Overload resolution works for simple cases, but as soon as you have complexity you're forced to add disjoint requirements, making everything more verbose. The rules are also complicated, subtle, and for a beginner it isn't clear how that would work.
Having the first case statement match is trivially easy to understand and means the execution order matches the reading order.
6
u/mcypark 1d ago edited 1d ago
Yeah, I understand the desire here. Especially coming from std::visit, it's very tempting. Though, I think we disagree on what makes std::variant more powerful than what other languages provide. In my opinion, the unique aspect is that we can handle the alternatives generically. IMO that does not necessarily mean that it must be done with overload resolution.
The bigger problem is how to do overload resolution on patterns outside of declaration patterns. For example, if we have predicate patterns:
bool less_than_five(int x) { return x < 5; }
bool is_even(int x) { return x % 2 == 0; }void f(int x) {
match (x) {
case less_than_five => /* handle < 5 */;
case is_even => /* handle even numbers >= 5 */;
}
}What would overload resolution do for this? There are other examples like this. e.g. with Case Ranges P4040 as patterns, you can have overlapping ranges that both match a value but neither are a "tighter fit", and stuff like that.
Or like:
match (point) {
case [int x, int y] => ;
case [0, _] => ;
case [_, 0] => ;
}If point is tuple(0, 0), what happens here?
The closest similar thing we have is partial specialization like:
template <int X, int Y>
struct S {};template <int Y>
struct S<0, Y> {};template <int X>
struct S<X, 0> {};These definitions are fine, until you actually instantiate S<0, 0> where you get an ambiguity error. But the thing is, point in our case is a runtime value.
I also think that the last comment about "what if there's no best ordering?" is actually an issue for best-match rather than first-match. With first match if there's no best ordering you can at least give it some ordering. If you do best match, and there's no best ordering, it just... doesn't work?
Anyway, couple of options I've considered:
If all of the patterns are declaration patterns, perform overload resolution on them. Otherwise, do first-match. -- I think this is bound to be very surprising when adding a non-declaration pattern changes the entire evaluation order.
A separate keyword to say we want overload resolution. Say for example like, match (x) overload { ... } or something like that. I think that would be feasible from a technical standpoint, but it doesn't seem worth the added complexity for the user.
So... yeah. The current rule is basically "first-exact-match", which is the closest we can get to order-independent first-match semantics.
0
u/crowbarous 1d ago
This is a good answer (in the sense that I understand the reasoning, not agree with it). I'll write more of my thoughts to you a bit later, perhaps tomorrow. (I might also choose a different avenue for that e.g. discord or email -- reddit is fine for submitting links and commenting on them, but it sucks at substantial conversations.) Thanks!
10
u/Salty-Paint-9700 2d ago
Anyone knows why it uses the => syntax instead of : like the switch?
I don't mind the new functionality, but all these new features have such inconsistent syntax (don't even get me started on ^^). Is it just because Rust has it like that or there's some parsing ambiguity issue? Ugh, C++ becomes such a garbage bag for mismatched (pun intended) stuff.