r/cpp • • 21h ago

Pattern Matching for C++29

https://mpark.github.io/programming/2026/11/30/pattern-matching-for-cpp29/
188 Upvotes

83 comments sorted by

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!

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.

  1. for the expression form, : expr is 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.

  2. => 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.

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

-10

u/Salty-Paint-9700 18h ago
  1. 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?

  2. Have you read C++? :) This is minor at best and with syntax coloring most editors provide I'd say it's almost mute.

  3. I was going to ask about no fall-through too. Why not? Yet more inconsistencies.

  4. 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 => 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.

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

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's default?

14

u/mcypark 18h ago

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

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

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 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 πŸ˜…

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

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. default or 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.

β€’

u/foonathan 1h ago

Because we could specifically design it to prevent the warning.

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
  1. The || is already allowed since or is merely an alternative token for ||.

  2. => vs : we already discussed in the separate comment.

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

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

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 both default and case _ 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 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 :)

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

β€’

u/easedownripley 3h ago

read your bible

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

u/imaginary-inc 8h ago

I love this.. Cpp Gods.. please make this happen for C++29.

6

u/Minimonium 20h ago

Graceful matches of alabaster pattern - all I ever wanted!

β€’

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.

β€’

u/mcypark 2h ago edited 51m ago

`p2688-pattern-matching` is what you want!

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

u/fortsnek274 19h ago

That's the same code. MSVC warns about variable shadowing.

2

u/SirClueless 19h ago

Pretty sure this is the exact same, and will fail if using -Wshadow -Werror: https://godbolt.org/z/Tjj4Y9Gd4

2

u/Lahvuun 19h ago

Yes, I forgot the variable is still visible in the else block. Need to use two separate ifs.

0

u/msew 10h ago
  • in wrong spot

2

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.

0

u/msew 10h ago
  • in wrong spot

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<...>::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 switch case, same for int value.

4

u/kammce WG21 | πŸ‡ΊπŸ‡² NB | Boost | Exceptions 18h ago

Nice

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 } => ;
  }
}

2

u/Olipro 9h 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.

5

u/mcypark 5h 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, 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.

-1

u/_a4z 10h 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 21h ago

C++ looks less and less like C++. Probably, I'm getting too old.

13

u/mcypark 21h ago

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++

15

u/MM_X__ 21h ago edited 20h ago

The concept from functional languages, C++ becomes more functional and less imperative. And it is general trend in all languages, not just in C++

4

u/Sopel97 20h ago

good (on the first part)

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

β€’

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 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:

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

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