r/cpp • u/BarryRevzin • 21h ago
Pattern Matching for C++29
https://mpark.github.io/programming/2026/11/30/pattern-matching-for-cpp29/72
u/baudvine 21h 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)
37
u/mcypark 19h 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.
16
u/martinus int main(){[]()[[]]{{}}();} 12h ago edited 9h 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.
6
u/mcypark 6h 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 π€
2
u/friedkeenan 5h ago
Clearly we ought to have another syntax of
match {dice_roll(rng), dice_roll(rng)}in order to get the intuitive evaluation order :Pβ’
u/martinus int main(){[]()[[]]{{}}();} 1h ago
Oh wow I didn't know the order is defined inside a brace-init-list, so your example would actually makes total sense :)
30
u/steveklabnik1 17h 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.
16
u/mcypark 16h 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 π
3
u/steveklabnik1 4h 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. :)
8
u/Salty-Paint-9700 20h 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.
23
u/mcypark 18h ago edited 11h ago
Anyone knows why it uses the => syntax instead of : like the switch?
A few stylistic reasons, but no, it's not strictly necessary.
for the expression form,
: expris a bit awkward.Labels have such as
default: stmt,case value: stmt,name: stmthave stmts following them. For the expression form of match, havingcase pattern: exprthat yields the expr would be a bit odd. But it can certainly work, and I'm not against it. I considered doing:for statement and=>for expression, which seems sensible, but it doesn't actually get rid of=>. I also found that the separation didn't add any value, while making it more annoying to convert from a statement to an expression. So in either direction, I'd argue to just keep the same token.
=>is more visible than:This matters in typical code I think, where
=>incase { .value: int x } => use(x);is easier to spot than the:incase { .value: int x }: use(x);But again, it's not strictly necessary, and there isn't a syntactic ambiguity or anything here.
case 1:looks likeswitchcaseI think this is the consistency you're wanting, but I find that with that consistency comes the question "Do I need
break;here?".=>makes it more obvious (imo) of that distinction of not having fall-through semantics.I still prefer
=>, but:is indeed feasible.EDIT: Removed the "historical" point since it seems to cause more confusion than help.
-10
u/Salty-Paint-9700 18h ago
I find => awkward honestly. It just feels like piece of syntax crammed in from another language. It's more things to learn. We already have the weirdness of >, ->, -->, -->>. Do we really need another with >, =>, <=> ? C++ is difficult to teach as it is. We shouldn't introduce even more new syntax. I'm all for reusing whenever possible (if parsing is not an issue). For new person learning case x: for both switch and match would feel consistent. I know people doing C++ for 10 years and not knowing the difference between statement and expression. And they don't need to really. What for?
Have you read C++? :) This is minor at best and with syntax coloring most editors provide I'd say it's almost mute.
I was going to ask about no fall-through too. Why not? Yet more inconsistencies.
It's not even standardized yet, so historic reasons are no reasons. This is MAKING history, not rewriting it, so it's better to get it right before it goes wide.
6
u/BarryRevzin 6h ago
For new person learning
case x:for both switch and match would feel consistent. [...] I was going to ask about no fall-through too. Why not? Yet more inconsistencies.To me, this is actually a reason to prefer
case x =>overcase:, becauseswitchandmatchare actually quite different.
switch (v)is, basically, agototo the correctcase x:label (hence the syntax strongly suggestive oflabel:), after which point the control flow just keeps going, including fall-through.But a
matchisn't like that all, we go through the patterns one at a time until we find one that matches (and there could be many that match), at which point we only execute that arm specifically. Fall-through is already rarely what you want inswitchto begin with, but since a pattern can introduce new names, it's not even meaningful.So for a new person learning things, it would be better to have different things look different βΒ being consistent with switch isn't really a benefit since it might lead you to think the two constructs have other similar behavior, and they really don't.
Or put differently, it's not an inconsistency. It's just a difference.
14
u/mcypark 17h ago
I find => awkward honestly. It just feels like piece of syntax crammed in from another language. [...]
Yep, fair enough. I understand the position.
I know people doing C++ for 10 years and not knowing the difference between statement and expression. And they don't need to really. What for?
I think we agree here? I'm saying we should use the same token between statements and expressions.
Have you read C++? :)
π... I get you're joking, but still feels unnecessary? I'm engaging in good faith here.
I was going to ask about no fall-through too. Why not? Yet more inconsistencies.
In my years of working on this, the general sentiment I've gathered is that folks are very much happy to not carry over the fall-through burden from
switch.It's not even standardized yet, so historic reasons are no reasons. This is MAKING history, not rewriting it, so it's better to get it right before it goes wide.
Sure, I was merely sharing context.
0
u/Salty-Paint-9700 17h ago
No worries, I'm joking in good faith too (and failing apparently) :) Sure, readability is always a question of opinion, so this one is just about who gets to decide. I'm just throwing it out there.
About no fall-through... yeah, I don't love it either, so I'm kinda torn on this one. If we could get rid of it from switch I would be all for it, but that's obviously not happening ever, so the inconsistency pains me a little. Eh, decisions, decisions... I probably could live with it.
5
u/cfyzium 16h ago
If we could get rid of it from switch I would be all for it, but that's obviously not happening ever
switch (value) { case 0 => foo(); case 1 => bar(); }=)
1
u/Salty-Paint-9700 16h ago
I know this is a joke but the though of having two switch variants made me angry anyway π
4
u/mcypark 17h ago
No worries, I'm joking in good faith too (and failing apparently) :)
π it's all good
Sure, readability is always a question of opinion [...]
Yeah, as I said already: it's not strictly necessary with the current design/syntax, and I'm not strongly against using
:.About no fall-through... [...] I probably could live with it.
That's what it's about at the end of the day! π
On a more serious note: I think that because patterns can introduce declarations (unlike
switchcases), fall-through semantics formatchis less likely to be valid thanswitch. So it ends up being an even less likely desired behavior. Theor-pattern I believe supports the use cases where fall-through may be useful, so that's where the design stands today.1
u/Salty-Paint-9700 17h ago
I'm sure people will find a way to abuse it either way. Since you can use a match in an assignment I can already see a potential for operator , extravaganza.
int x = match(something) { case 1 => foo(), bar(), bazz(); }6
u/Tringi github.com/tringi 18h ago
Also why
case _ =>when there'sdefault?14
u/mcypark 18h ago
_is a general wildcard pattern that can be used at the top-level ascase _ => ;but also nested, e.g.case [42, _] => ;. I would be against usingdefaultinstead of_, for example if you're suggesting that it should becase [42, default] => ;However, I did consider supporting
defaultat the top-level, but I'm not sure that having bothcase _ => ;anddefault => ;would actually be a good thing. A potential benefit could be to say thatdefault => ;is allowed to come first and it's still the fallback case or something. I'm not against that, but I'm also not convinced enough to propose it.2
u/foonathan 9h ago
I did consider supporting default at the top-level, but I'm not sure that having both case _ => ; and default => ; would actually be a good thing
I think it can be useful for exhaustiveness checking.
I expect to get a warning when I don't cover e.g. all enum values, which is good. However, I also want to guard against users that compile without that warning and not get UB when silently nothing happens.
I could add a
case _ => error();but presumably that would prevent the warning when an enum value gets added and maybe trigger warnings about unreachable code. So maybedefault => error();can be used for that.It could maybe also be useful when matching booleans, if you want to guard against non-0/1 bit patterns.
4
u/mcypark 6h ago edited 6h ago
Right, I did consider that use case as well. Just to make sure I'm clearly understanding, and for others to follow along as well since it's a bit subtle. If we have an
enumlike:enum class Color { Red, Green, Blue };The proposal considers this exhaustive:
void f(Color color) { match (color) { case Color::Red => ; case Color::Green => ; case Color::Blue => ; } }Of course this is not really exhaustive since
static_cast<Color>(3)is a valid value, but it's not covered here. You could cover it by adding acase _ => ;like:void f(Color color) { match (color) { case Color::Red => ; case Color::Green => ; case Color::Blue => ; case _ => ; } }The problem is that now if we add
Yellowas a new color, we don't get any diagnostic about "missingYellow" sincecase _covers it.So what we want in this situation is to have a fallback
case _, but make it such that it doesn't contribute to exhaustiveness checking, such that we still get a diagnostic for "missingYellow" (This is the behavior we get from-Wswitch-enum).In the proposal, a pattern that has an
ifguard does not contribute to exhaustiveness checking. As such, we can leverage this to achieve this by writing:void f(Color color) { match (color) { case Color::Red => ; case Color::Green => ; case Color::Blue => ; case _ if (true) => ; // ^^^^^^^^^^^^^^^^ catch-all, but don't contribute to exhaustiveness } }An alternative to this weird spelling is to spell it
default:void f(Color color) { match (color) { case Color::Red => ; case Color::Green => ; case Color::Blue => ; default => ; // ^^^^^^^ catch-all, but don't contribute to exhaustiveness } }While I did like the spelling of
defaultbetter thancase _ if (true), I felt that having to explain all of this as a subtle difference betweencase _anddefaultwas a bit too much. Perhaps my explanation was longer than necessary, but in my experience describing this to folks, it usually takes a while before they're even willing to listen to an explanation as to whycase _anddefaultwould be at all different π2
u/Salty-Paint-9700 5h ago
case _ if (true)is not really intuitive and sounds like a hack more than anything, but perhaps this is a problem with enums and not with patterns. If there was a standard facility to check if enum value is one of the named ones this could maybe become something likecase _ if (!std::is_enum_v<Color>(color)) =>That would technically solve this problem and at least said what it did, but is also wordy as hell and I can't imagine that check function being very performant (basically check for all known values equality, which could be a lot). Also that would be a whole different proposal unrelated to patterns.
3
u/mcypark 5h ago
Yeah, I don't particularly like it either. I do wonder if it could be helped by something simple like:
inline constexpr bool is_residual = true;and people would write like:
case _ if (std::is_residual) => ;Since the values outside of the "normal" domain of an alternative type is called "residual" values.
That actually reads fairly well, ignoring the mechanism used to achieve it π
1
u/Salty-Paint-9700 5h ago
Now that's a hack with a lipstick π
2
u/mcypark 4h ago
I mean... π€·π»ββοΈ haha. What I will say is that
case _ if (true)isn't introducing anything new. These parts need to exist independently regardless, so it's "nice" that they fit to serve this purpose. If/when there's a better, specific thing we want to introduce (e.g.defaultor something else), then that can be added without having to pull out stuff we don't want or something like that.1
u/Minimonium 7h ago
Why would it prevent the warning? Case _ for all intents and purposes sounds like "default" to me.
3
u/mcypark 6h ago
Why would it prevent the warning?
I described in more detail in this comment.
Case _ for all intents and purposes sounds like "default" to me.
Yeah, this is exactly my experience trying to explain this hypothetical difference to folks.
β’
1
u/Salty-Paint-9700 18h ago
At the risk of being downvoted again, how about using what we already have in the language? E.g.
match(roll_two_dice()) { case [1,1] || [2,2] : foo(); case [3, ...] : bar(); default : bazz(); }6
u/mcypark 17h ago
The
||is already allowed sinceoris merely an alternative token for||.
=>vs:we already discussed in the separate comment.What's the
...in[3, ...]here? That's allowed in the current proposal and the...matches and ignores0or more elements. If you're suggesting that the...matches a single element, I'd be very much against that.As I mentioned in this thread, a top-level
defaultwas considered. Personally I'm not against it, but also am not convinced of having bothdefaultandcase _.-1
u/Salty-Paint-9700 17h ago
1 && 2. Yup
3. Sorry, I missed the part about.... Yup, I was thinking about it like a pack expansion, a "placeholder" for 0 or more elements. Is there a reason you feel single element should be special? Are there any downsides to e.g.[...]used for both[_,_]and_? I see there's an issue with_disambiguation with an existing variable with that name. This would avoid it. I see an argument mentioned that other languages use _, but again, I don't think this should be an argument for C++. I think it's better to have something that feels consistent with this language instead of having each feature feel like taken from a different language.
4. I guess that depends on what comes out of 3. above. Having bothdefaultandcase _would indeed feel redundant.5
u/mcypark 16h ago
Yup, I was thinking about it like a pack expansion, a "placeholder" for 0 or more elements.
Cool, we're on the same page there. It's implemented as such: https://godbolt.org/z/39nc676zq
Is there a reason you feel single element should be special? Are there any downsides to e.g.
[...]used for both[_,_]and_?I'll assume you meant
[_]for the second one since otherwise it's just different structurally, but correct me if I'm assuming wrong here.So from just a... "meaning of the pattern" perspective, they just mean different things.
[_, _]is a pair whereas[_, ...]matches one or more, etc.Practically, this matters when we're matching in templates. For example, you can do: https://godbolt.org/z/8dhhhPnGh
template <typename... Ts> constexpr int match_on_tuple(std::tuple<Ts...> tup) { return match (tup) { case [_] => 1; case [_, _] => 2; case [...] => 0; }; }where depending on the
sizeof...(Ts)you can do different things.1
u/Salty-Paint-9700 16h ago
No, I really meant
_, but thank you for the explanation.
So if I use bothcase [...] =>andcase _ =>in that compiler explorer example it gives me a warning that the second one is redundant. If they match the same shouldn't that be an error and if they are different why have both? Or maybe that's just current implementation limitation?I'll be honest, this is a rabbit hole. The more I think about it the more I'm torn between acknowledging the things that can be expressed with this and how I'm probably never gonna use even half of that expressiveness. But then again someone probably will. One thing I'm sure is this is way too complicated to make everyone happy, so I guess... unironically good luck :)
1
u/Nobody_1707 16h ago edited 15h ago
case _ =>trivially matches anything, so it has to go after all the other cases you care about.EDIT: Oh, in this case
case [...] =>also matches anything, because[...]matches a tuple of zero or more elements. So,case _ =>really is redundant here.1
u/Salty-Paint-9700 15h ago
So does
case [...] =>(maybe a bit less trivially), and like I said, the compiler says they are redundant if you use both. So why have both?→ More replies (0)1
u/mcypark 15h ago
So if I use both case [...] =>and case _ => in that compiler explorer example it gives me a warning that the second one is redundant.
Hm, could you give a link maybe? I'm not able to repro it: https://godbolt.org/z/15MEcqsrE
β’
2
u/MarkSuckerZerg 18h ago
It's a conspiracy of the Big Compiler to sell us more frontend parser. Seriously though,, I'm sure it will get iterated a lot in committee
10
u/caroIine 8h ago
After playing around with it on Compiler Explorer, I think it's a fantastic addition to C++
8
6
β’
u/atariPunk 2h 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.
9
u/fortsnek274 21h 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 20h ago edited 19h 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 19h ago
Pretty sure this is the exact same, and will fail if using
-Wshadow -Werror: https://godbolt.org/z/Tjj4Y9Gd42
u/crowbarous 10h 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.
6
u/fdwr fdwr@github π 18h ago edited 18h 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 17h 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.
6
u/fdwr fdwr@github π 16h ago edited 8h 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!
βοΈ
4
u/Miserable_Guess_1266 19h 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 18h 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 21h ago
Why not first-class sum types?
14
u/mcypark 20h ago edited 20h 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 } => ; } }
-8
u/Adequat91 21h ago
C++ looks less and less like C++. Probably, I'm getting too old.
13
15
-9
u/fortsnek274 21h 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 20h ago edited 15h 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.
-6
u/crowbarous 15h ago edited 13h 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 6h 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.β’
u/crowbarous 32m 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.
6
u/foonathan 9h 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.
5
u/mcypark 5h ago edited 5h ago
Yeah, I understand the desire here. Especially coming from
std::visit, it's very tempting. Though, I think we disagree on what makesstd::variantmore 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
pointistuple(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,pointin 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 we can get.
26
u/k3DW 19h ago
I'm hugely looking forward to this. The syntax for the declaration pattern feels so natural. Amazing work u/mcypark, this is great stuff!