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.
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: stmt have stmts following them. For the expression form of match, having case pattern: expr that 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 => in case { .value: int x } => use(x); is easier to spot than the : in case { .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 like switch case
I 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.
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.
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 => over case:, because switch and match are actually quite different.
switch (v) is, basically, a goto to the correct case x: label (hence the syntax strongly suggestive of label:), after which point the control flow just keeps going, including fall-through.
But a match isn'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 in switch to 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.
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.
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.
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 switch cases), fall-through semantics for match is less likely to be valid than switch. So it ends up being an even less likely desired behavior. The or-pattern I believe supports the use cases where fall-through may be useful, so that's where the design stands today.
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();
}
_ is a general wildcard pattern that can be used at the top-level as case _ => ; but also nested, e.g. case [42, _] => ;. I would be against using default instead of _, for example if you're suggesting that it should be case [42, default] => ;
However, 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. A potential benefit could be to say that default => ; 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.
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 maybe default => 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.
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 enum like:
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 a case _ => ; 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 Yellow as a new color, we don't get any diagnostic about "missing Yellow" since case _ 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 "missing Yellow" (This is the behavior we get from -Wswitch-enum).
In the proposal, a pattern that has an if guard 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 default better than case _ if (true), I felt that having to explain all of this as a subtle difference between case _ and default was 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 why case _ and default would be at all different π
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 like case _ 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.
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. default or something else), then that can be added without having to pull out stuff we don't want or something like that.
The || is already allowed since or is 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 ignores 0 or 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 default was considered. Personally I'm not against it, but also am not convinced of having both default and case _.
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 both default and case _ would indeed feel redundant.
No, I really meant _, but thank you for the explanation. So if I use both case [...] =>and case _ => 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 :)
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.
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 statementsandexpressions 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.
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 π€
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.
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 π
: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. :)
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.
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.
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 π€.
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.
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`?
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<...>::alternatives to determine the projectable states, and computes the type/value category of get<Idx>(subject) for each projectable state. The Idxs for which get<Idx>(subject) matches the float error are used in the lowering of the switchcase, same for int value.
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>intmain(){
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 140733546207224
The 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.
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, 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.
Do you mind sharing which parts don't look like C++? Genuinely curious since I put in a lot of effort with the goal of keeping things look and feel like C++
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β.
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.
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.
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...
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::visit you implicitly converted to double on the way into the visitor, here we need to do it on the way out (or explicitly yield double(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's floating_point, "floating point". Otherwise, if it's integral, "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.
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.
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 overload as 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.
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.
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:
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 we can get.
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 1d 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.
72
u/baudvine 1d 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)
17
u/martinus int main(){[]()[[]]{{}}();} 18h ago edited 15h ago
For
match (dice_roll(), dice_roll()), is the call order defined? E.g. when using it with arnglike so:where each call modifies the state of
rngI'd very much want this to be deterministic and not depend on the compiler.32
u/steveklabnik1 23h 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.
25
u/k3DW 1d 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!
5
u/atariPunk 8h 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/caroIine 14h ago
After playing around with it on Compiler Explorer, I think it's a fantastic addition to C++
7
u/fdwr fdwr@github π 1d ago edited 1d ago
Love the consistent ordering of
match (foo) {}likeswitch (foo) {}, versus the previously inconsistentfoo match {}. Yay for cleaner code.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"Does that also play nicely with case ranges
1 ... 3proposed here by u/eisenwave, like C case ranges? I see...mentioned for pack expansion, but not case ranges.7
u/imaginary-inc 14h ago
I love this.. Cpp Gods.. please make this happen for C++29.
5
u/Minimonium 1d ago
Graceful matches of alabaster pattern - all I ever wanted!
8
u/fortsnek274 1d ago
And one of the irritants is that when I do something like that:
The variables have to have a different name as they stay in scope.
4
u/Miserable_Guess_1266 1d 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:
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/kammce WG21 | πΊπ² NB | Boost | Exceptions 1d ago
Nice
8
u/sweetno 1d ago
Why not first-class sum types?
2
u/martinus int main(){[]()[[]]{{}}();} 4h ago
I think there is a problem in the paper when a guard modifies the subject. From section 12.3:
Here is an example:
The first case matches, then the guard assigns an
intbut fails. After that the variant holds anint, so I'd say thecase { int i }should match. But the prototype gives this instead: https://godbolt.org/z/bx4zqfqjzand prints
The 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.
1
u/Olipro 15h 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.
-1
u/_a4z 16h ago
We should ditch contracts, get a C++27, and pull in the things from 29 that are ready, like pattern matching.
And then have a yearly update of C++
-8
u/Adequat91 1d ago
C++ looks less and less like C++. Probably, I'm getting too old.
-6
u/crowbarous 21h ago edited 19h ago
...
...
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.
...
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...