TL;DR: Pattern matching takes complex code such as:
return std::visit(
[&](const auto &S) -> llvm::Error {
using T = std::decay_t<decltype(S)>;
if constexpr (std::is_same_v<T, TUSummary>) {
return writeTUSummary(S, Path);
} else if constexpr (std::is_same_v<T, LUSummary>) {
return writeLUSummary(S, Path);
} else {
static_assert(std::is_same_v<T, WPASuite>,
"Artifact visitor must cover all variant alternatives");
return writeWPASuite(S, Path);
}
},
A);
and simplifies it to:
return match (A) {
case { const TUSummary &S } => writeTUSummary(S, Path);
case { const LUSummary &S } => writeLUSummary(S, Path);
case { const WPASuite &S } => writeWPASuite(S, Path);
};
EWG discussed P2688R6 in Búzios, and took the following poll (EWG Paper Tracker):
EWG encourages more work in direction of P2688R6
SF F N A SA 33 11 2 0 0 Result: Consensus
My plan is to bring wording to the Istanbul meeting in March 2027. The feedback on this latest design has been overwhelmingly positive. As C++26 wraps up (🤞), we should move now for pattern matching to make it in C++29.
Introduction
Last week, I attended the C++ committee meeting held in Búzios, Brazil. This was my first in-person meeting in about 2.5 years, the last one having been the St. Louis meeting in June 2024. After that, I attended meetings remotely to be present with my wife during her pregnancy.
Last time I presented pattern matching in EWG (remotely) was at the Hagenberg
meeting in Feb 2025, where P2688R5 was being considered for C++26
(EWG Paper Tracker).
The “forward to CWG for inclusion in C++26” poll resulted in 20/11/6/13/5,
and did not gain consensus.
While I was somewhat dejected with the result, I also agreed with the sentiment.
A few months later, in May 2025, my son was born 🎉. Needless to say, I decided to give pattern matching a bit of a rest, and be fully present with my family.
Almost 1.5 years later, I submitted P2688R6 in
Sept 2026. It still offers pattern composition, as I consider it to be an
absolute non-negotiable for pattern matching (as I argued in
P2688R0). However, it challenged a lot of decisions
made in R5. For example, R6 uses existing declaration syntax to introduce new
names instead of let, replaces infix match with a prefix context-sensitive
match (i.e. match (x) { ... }), and includes exhaustiveness checking.
I was absolutely stoked to present this in Búzios. Silly me, I thought we were
going to be discussing C++29 features at this meeting! Instead, most of the week
ended up being dedicated to resolving the disapproval of the DIS. There’s been
more than enough discussion about that in published papers, r/cpp,
etc, so I won’t be discussing any of that in this post.
Since most of the post-meeting discourse will likely be dominated by Contracts discussions as well, I’ll give an update of the latest pattern matching proposal in this post.
A Tour of P2688R6
We’ll focus on user-side examples in this post, adapted from section 2.1 Using Pattern Matching.
For a library-side example, please refer to 2.2 Customizing an Alternative Type.
The implementation of the proposal is available on Compiler Explorer under
x86-64 clang (pattern matching - P2688). The code lives at this branch:p2688-pattern-matching. The examples from this section can be found at https://godbolt.org/z/GefYrqs8o, so you can try stuff out as we go along.
The following coin example is adapted from The Rust Programming Language book, Chapter 6.2:
enum class Coin { Penny, Nickel, Dime, Quarter };
int value_in_cents(Coin coin) {
return match (coin) {
case Coin::Penny => 1;
// ^^^^^^^^^^^ value pattern
case Coin::Nickel => 5;
case Coin::Dime => 10;
case Coin::Quarter => 25;
};
}
This is a match expression, so the expression in the selected handler
provides its value. A value pattern such as Coin::Penny matches if
the subject has the same value. Exhaustiveness checking is required in general.
For an enum, every enumerator value is required to be covered. Therefore,
omitting the Coin::Quarter case is ill-formed:
error: match expression is not exhaustive; example of a missing case: Quarter
Next, let’s consider a dice roll example from the same chapter:
int dice_roll();
void take_turn() {
match (dice_roll()) {
case 3 => add_fancy_hat();
case 7 => remove_fancy_hat();
case int roll => move_player(roll);
// ^^^^^^^^ declaration pattern
}
}
This is a match statement, so the statement in the selected handler is
executed. dice_roll() is evaluated exactly once. The declaration pattern
(int roll) matches every other result and initializes roll from it.
3and7are just expressions, so if we had a constant namedsevenwith value7,case sevenwould have the same effect ascase 7.
If every result other than 3 or 7 should simply be re-rolled, its value can
be ignored with a wildcard pattern (_):
match (dice_roll()) {
case 3 => add_fancy_hat();
case 7 => remove_fancy_hat();
case _ => reroll();
// ^ wildcard pattern
}
Patterns can also be combined with or. An or-pattern tries its alternatives
against the same subject from left to right and matches when one succeeds:
match (dice_roll()) {
case 1 or 2 => lose_turn();
// ^^^^^^ or-pattern
case 3 => add_fancy_hat();
case 7 => remove_fancy_hat();
case int roll => move_player(roll);
}
Suppose now that we roll two dice and return them as a std::pair:
std::pair<int, int> roll_two_dice();
static constexpr int six = 6;
match (roll_two_dice()) {
case [1, 1] => snake_eyes();
// ^^^^^^ decomposition pattern
case [six, six] => boxcars();
case [int r1, int r2] => {
move_player(r1 + r2);
}
}
[P1, P2] is a decomposition pattern. It recursively matches the two
elements. The [1, 1] pattern matches if both elements are 1.
Each six in the pattern [six, six] is a nested value pattern that refers
to the existing variable. The [int r1, int r2] pattern binds each element
to the corresponding, nested declaration pattern.
In this example, we could also use structured bindings and write
case auto [r1, r2]instead ofcase [int r1, int r2]. However, note thatcase [six, six]or a mixed use such ascase [six, int r2]are not expressible with structured bindings.
After a pattern matches, if there is an if guard present, the handler is taken
if the guard evaluates to true. Otherwise, the next match case is considered.
For example, we can handle the hardway rolls (doubles other than 1 and 6) like
this:
std::pair<int, int> roll_two_dice();
static constexpr int six = 6;
match (roll_two_dice()) {
case [1, 1] => snake_eyes();
case [six, six] => boxcars();
case [int r1, int r2] if (r1 == r2) => hardways(r1);
// ^^^^^^^^^^^^^ if guard
case [int r1, int r2] => {
move_player(r1 + r2);
}
}
Alternatively, a match can match two separate values directly.
Multiple subjects form an unnamed type and are matched together.
// std::pair<int, int> roll_two_dice();
static constexpr int six = 6;
match (dice_roll(), dice_roll()) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ multiple subjects
case [1, 1] => snake_eyes();
case [six, six] => boxcars();
case [int r1, int r2] if (r1 == r2) => hardways(r1);
case [int r1, int r2] => {
move_player(r1 + r2);
}
}
Let’s shift gears and look at alternative types. Suppose our die may roll off
the table, and its result therefore is a std::optional:
std::optional<int> try_dice_roll();
match (try_dice_roll()) {
case { int roll } => move_player(roll);
// ^^^^^^^^^^^^ alternative pattern
case {} => roll_again();
}
{ P } projects the int inside the optional, if present, and recursively
applies P to it. In this example, P is the declaration pattern int roll.
{} matches the optional’s empty state.
Let’s extend this to the two dice example from above and return
an std::optional<std::pair<int, int>>.
std::optional<std::pair<int, int>> try_roll_two_dice();
static constexpr int six = 6;
match (try_roll_two_dice()) {
case { [1, 1] } => snake_eyes();
case { [six, six] } => boxcars();
case { [int r1, int r2] } if (r1 == r2) => hardways(r1);
case { [int r1, int r2] } => move_player(r1 + r2);
case {} => roll_again();
}
You may notice that all of the patterns [1, 1], [six, six],
[int r1, int r2] are exactly as they were in the previous example,
only that now they’re wrapped in { ... }.
This is recursive pattern composition at play. The braces project the contained alternative, and the nested pattern is matched against that projection. This property of patterns is maintained consistently throughout.
Let’s move onto std::variant, which can have several different alternatives:
using SearchResult = std::variant<File, Directory>;
void open(const SearchResult& result) {
match (result) {
case { const File& file } => open_file(file);
case { const Directory& directory } => open_directory(directory);
}
}
Each declaration pattern matches an alternative whose payload has the corresponding type and introduces a name for that payload in the handler.
A std::expected result can be matched similarly to a variant:
std::expected<int, std::string> parse_port(std::string_view text);
match (parse_port(text)) {
case { int port } => connect(port);
case { const std::string& message } => report(message);
}
Note that the value and error types of expected can be the same.
std::expected<std::string, std::string> in particular comes up often in
practice. In that case, named selectors can be used to distinguish the
alternatives:
std::expected<std::string, std::string> read_file(std::string_view path);
auto result = read_file(path);
match (result) {
case { .value: const auto& contents } => process(contents);
// ^^^^^^ named selector
case { .error: const auto& message } => report(message);
}
A declaration pattern can use dynamic_cast semantics when applied to a
polymorphic class subject.
struct Shape { virtual ~Shape() = default; };
struct Circle : Shape { double radius() const; };
struct Rectangle : Shape {
double width() const;
double height() const;
};
double compute_area(const Shape& shape) {
return match (shape) {
case const Circle& c => std::numbers::pi * c.radius() * c.radius();
case const Rectangle& r => r.width() * r.height();
case _ => throw std::invalid_argument("unknown shape");
};
}
The wildcard covers other classes that may derive from Shape.
Patterns can also be used in boolean tests and control-flow conditions:
SearchResult result = search(path);
// boolean-yielding single-pattern test expression
bool is_file = match(result, case { const File& });
// pattern condition
if (case { const Directory& directory } = result) {
open_directory(directory);
}
const File& is a declaration pattern with an omitted name. It tests whether
the corresponding declaration could be initialized, but does not perform that
initialization.
A single-pattern test produces bool whether the pattern matched or not.
A pattern condition additionally makes names introduced by its pattern
available in subsequent conditions and the successful branch.
Real Examples
Let’s take a look at some real examples. I’ve been trying out using pattern
matching in the Clang/LLVM codebase itself at a branch (p2688-selfhost),
and building it with Clang that was built off of p2688-pattern-matching.
Variant Dispatch
Let’s take a look at the body of JSONFormat::writeArtifact from Clang.
Given A of type std::variant<TUSummary, LUSummary, WPASuite>:
return std::visit(
[&](const auto &S) -> llvm::Error {
using T = std::decay_t<decltype(S)>;
if constexpr (std::is_same_v<T, TUSummary>) {
return writeTUSummary(S, Path);
} else if constexpr (std::is_same_v<T, LUSummary>) {
return writeLUSummary(S, Path);
} else {
static_assert(std::is_same_v<T, WPASuite>,
"Artifact visitor must cover all variant alternatives");
return writeWPASuite(S, Path);
}
},
A);
This becomes:
return match (A) {
case { const TUSummary &S } => writeTUSummary(S, Path);
case { const LUSummary &S } => writeLUSummary(S, Path);
case { const WPASuite &S } => writeWPASuite(S, Path);
};
No generic lambda, no std::decay_t, no decltype, no if constexpr, no std::is_same_v, no static_assert.
LLDB Response
This example is from LLDB in a response serialization function, toJSON.
R.message is of type std::optional<std::variant<ResponseMessage, String>>.
if (R.message) {
if (const auto *messageEnum =
std::get_if<ResponseMessage>(&*R.message)) {
switch (*messageEnum) {
case eResponseMessageCancelled:
Result.insert({"message", "cancelled"});
break;
case eResponseMessageNotStopped:
Result.insert({"message", "notStopped"});
break;
}
} else if (const auto *messageString =
std::get_if<String>(&*R.message)) {
Result.insert({"message", *messageString});
}
}
There are 3 levels of nested-ness here. The top-level is checking the state of
optional, the next is dispatching on the variant using std::get_if, and
the last is a switch in the ResponseMessage case.
We can collapse these levels into the patterns themselves, again leveraging pattern composition, resulting in an overall flat construct:
match (R.message) {
case {} => ;
case { { eResponseMessageCancelled } } => Result.insert({"message", "cancelled"});
case { { eResponseMessageNotStopped } } => Result.insert({"message", "notStopped"});
case { { const String &message } } => Result.insert({"message", message});
}
We do nothing for an empty optional. For the rest, the outer { ... } unwraps
the optional, and the inner { ... } unwraps the variant. Value matching
on enum automatically provides switch dispatch behavior.
Custom RTTI
It turns out that more projects than I thought roll their own custom RTTI mechanism. One such example is ubiquitous in Clang/LLVM itself.
Refer to How to set up LLVM-style RTTI for your class hierarchy for more information.
One of the class hierarchies in Clang is rooted at Decl. There are derived
classes such as FunctionDecl and VarDecl that inherit from Decl. There
is also a parallel enum that represents each of the derived classes.
Given a D of type Decl*, there are two general dispatch mechanisms used
throughout Clang:
Assume for this example that the only derived classes of
DeclareFunctionDeclandVarDecl.
switch + cast | dyn_cast |
|---|---|
|
|
The “switch + cast” approach has the benefit that you get at least a form of
exhaustiveness checking, since most compilers provide warnings on missing
enumerators when matching on an enum. The downsides are that (1) you have to
know about the existence of the parallel enum at all, and (2) this mapping
needs to be maintained. For example, case Decl::Function must be paired with
cast<FunctionDecl>(D).
The “dyn_cast” approach has the benefit that you don’t have to know about the
parallel enum at all. You can just dyn_cast<FunctionDecl>(D) and that’s it.
The downsides are that (1) you don’t get exhaustiveness checking, since it’s
just a chain of if/else if at the end of the day, and (2) it can be
a performance penalty since the sequence of dyn_cast may not optimize as well
as a switch + cast.
With Decl opted into alternative_traits, we can get the best of both:
match (*D) {
case { const FunctionDecl& FD } => use(&FD);
case { const VarDecl& VD } => use(&VD);
}
No need to know about the parallel enum, no need to maintain mappings, you get
exhaustiveness checking, and the compiler can lower the dispatch to a switch,
which can perform better than a sequence of if/else if.
Sub-Hierarchies (Bonus)
This is something I did not have time to present to EWG, but it’s interesting enough that I want to cover here.
Within the Decl hierarchy, there are some sub-hierarchies as well.
For example, ObjCContainerDecl inherits from Decl and has 5 concrete classes
under it.
This example comes from USRGenerator::VisitObjCContainerDecl in Clang.
Given D of type const ObjCContainerDecl*, it uses the “switch + cast”
approach like this:
switch (D->getKind()) {
default:
llvm_unreachable("Invalid ObjC container.");
case Decl::ObjCInterface:
case Decl::ObjCImplementation:
GenObjCClass(...);
break;
case Decl::ObjCCategory:
GenObjCCategory(...);
break;
case Decl::ObjCCategoryImpl:
GenObjCCategory(...);
break;
case Decl::ObjCProtocol:
GenObjCProtocol(...);
break;
}
Earlier, I said that “switch + cast” offers at least a form of
exhaustiveness checking. But here, we’ve lost it.
The default: llvm_unreachable(...); is present because getKind() still
returns a Decl::Kind, even if we’re constrained to ObjCContainerDecl here.
There is no separate ObjCContainerDecl::Kind that returns only the 5 options.
However, the alternative_traits opt-in mechanism allows specializing
alternative_traits<ObjCContainerDecl> specifically. That specialization lists
the 5 concrete derived classes directly, and we regain exhaustiveness checking.
The usage code would look like:
match (*D) {
case { const ObjCInterfaceDecl& } or
{ const ObjCImplementationDecl& } => GenObjCClass(...);
case { const ObjCCategoryDecl& CD } => GenObjCCategory(...);
case { const ObjCCategoryImplDecl& CD } => GenObjCCategory(...);
case { const ObjCProtocolDecl& PD } => GenObjCProtocol(...);
}
In p2688-selfhost, the codegen mechanism is updated such that
the alternative_traits specializations are automatically generated for
Decl, Stmt, and the intermediate nodes such as ObjCContainerDecl
in DeclNodes.td
and StmtNodes.td.
Directional Consensus in EWG
P2688R6 was discussed on Thurs afternoon in EWG. The presented slides: P2688R6.slides.html.
EWG took the following poll (EWG Paper Tracker):
EWG encourages more work in direction of P2688R6
SF F N A SA 33 11 2 0 0 Result: 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”.
Folks who were in favor of R5 are even more strongly in favor of R6, and several who were against R5 have told me that they are now in favor of R6. Personally, this is the most confident, optimistic, and satisfied I’ve been with the design.
What’s Next
I plan to bring wording for P2688 to the Istanbul meeting, as well as the library companion paper for LEWG. The ambitious goal is to have the proposal forwarded to CWG for C++29. Realistically, it’ll need a few more meetings to get to that point.
The following is an adapted timeline from P1000R8:
| Meeting | Milestone |
|---|---|
| 2026.2 - Brno | First meeting of C++29 |
| 2026.3 - Búzios | Try to front-load “big” language features including ones with broad library impact (incl. try to merge TSes here) |
| We are here | |
| 2027.1 - Istanbul | |
| 2027.2 - Sofia | |
| 2027.3 - Budapest (tentative) | EWG: Last meeting for new C++29 language proposals we haven’t seen before. EWG → LEWG: Last meeting to approve C++29 features needing library response. LEWG: Focus on progressing papers on how to react to new language features. |
| 2028.1 - Kona | * → CWG, LWG: Last meeting to send proposals to wording review (incl. TS merges). C++29 design is feature-complete. |
We have 4 meetings until we call C++29 feature complete. So we really don’t have that many more meetings left. If we’re serious about shipping pattern matching in C++29, we’ve gotta get moving.
Thanks to Barry Revzin and Zach Laine for reviewing, and providing feedback on this post!