match and
casehttps://mpark.github.io/wg21-papers/staging/match/P2688R6.slides.html
Michael Park
Document #:P2688R6 Latest StatusDate:2026-11-19Project:Programming Language C++Audience:EvolutionReply-to:Michael
Park
<mcypark@gmail.com>
2026-11-19
x86-64 clang (pattern matching - P2688).p2688-pattern-matching.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;
};
}match
can be a statement or an expression.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;
// error: match expression is not exhaustive; example of a missing case: Quarter
};
}match
can be a statement or an expression.int dice_roll();
void add_fancy_hat();
void remove_fancy_hat();
void move_player(int spaces);
void take_turn() {
match (dice_roll()) {
case 3 => add_fancy_hat();
case 7 => remove_fancy_hat();
case int roll => move_player(roll);
// ^^^^^^^^ declaration pattern
}
}A declaration pattern binds its current subject directly.
void reroll();
void reroll_unless_special() {
match (dice_roll()) {
case 3 => add_fancy_hat();
case 7 => remove_fancy_hat();
case _ => reroll();
// ^ wildcard pattern
}
}_ always matches without
introducing a name.
bool is_even(int value) { return value % 2 == 0; }
bool is_even_roll(int roll) {
return match (roll) {
case is_even => true;
// ^^^^^^^ predicate pattern
case _ => false;
};
}A predicate pattern invokes a callable with the current subject.
void lose_turn();
void take_turn_with_or_pattern() {
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);
}
}An
or-pattern
tries its sub-patterns against the same subject.
std::pair<int, int> roll_two_dice();
void snake_eyes();
void boxcars();
void take_turn_with_pair() {
match (roll_two_dice()) {
case [1, 1] => snake_eyes();
// ^^^^^^ decomposition pattern
case [6, 6] => boxcars();
case [int a, int b] => move_player(a + b);
}
}A decomposition pattern uses structured bindings to obtain the elements, then matches each element with its corresponding nested pattern.
void play_doubles(int roll);
void take_turn_with_guard() {
match (roll_two_dice()) {
case [1, 1] => snake_eyes();
case [6, 6] => boxcars();
case [int a, int b] if (a == b) => play_doubles(a);
case [int a, int b] => move_player(a + b);
}
}A guard tests a condition after its pattern succeeds.
void take_turn_with_two_subjects() {
match (dice_roll(), dice_roll()) {
case [1, 1] => snake_eyes();
case [6, 6] => boxcars();
case [int a, int b] if (a == b) => play_doubles(a);
case [int a, int b] => move_player(a + b);
}
}Multiple subjects form an implicit unnamed product.
std::optional<int> try_dice_roll();
void roll_again();
void take_optional_turn() {
match (try_dice_roll()) {
case { int roll } => move_player(roll);
// ^^^^^^^^^^^^ alternative pattern
case {} => roll_again();
}
}{ P }
matches the subject when P matches
the projection of an active alternative.
{} matches
the empty optional.
struct File { std::string name; };
struct Directory { std::string name; };
using SearchResult = std::variant<File, Directory>;
void open_file(const File&);
void open_directory(const Directory&);
void open(const SearchResult& result) {
match (result) {
case { const File& file } => open_file(file);
case { const Directory& directory } => open_directory(directory);
}
}The declaration patterns bind the stored
File or
Directory.
std::expected<int, std::string> parse_port(std::string_view text);
void connect(int port);
void report(const std::string& message);
void connect_from(std::string_view text) {
match (parse_port(text)) {
case { int port } => connect(port);
case { const std::string& message } => report(message);
}
}The value and error types are different, so declaration patterns can be used to distinguish them.
std::expected<void, std::string> start_server(int port);
void report(const std::string& message);
void start(int port) {
match (start_server(port)) {
case { void } => ;
case { const std::string& message } => report(message);
}
}The success alternative has type
void, with
no value to bind.
std::expected<std::string, std::string> read_file(std::string_view path);
void process(const std::string& contents);
void report(const std::string& message);
void read_config(std::string_view path) {
match (read_file(path)) {
case { .value: const auto& contents } => process(contents);
case { .error: const auto& message } => report(message);
}
}The value and error here have the same type. Named selectors can be used to distinguish them.
#include <stdexcept>
struct Shape { virtual ~Shape() = default; };
struct Circle : Shape { double radius() const; };
struct Triangle : Shape { double base() const; double height() const; };
struct Rectangle : Shape { double width() const; double height() const; };
struct Square : Rectangle { /* ... */ };
double compute_area(const Shape& shape) {
return match (shape) {
case const Circle& c => 3.14 * c.radius() * c.radius();
case const Triangle& t => 0.5 * t.base() * t.height();
case const Rectangle& r => r.width() * r.height();
case _ => throw std::invalid_argument("unknown shape");
};
}Polymorphic matching has
dynamic_cast
semantics.
Consecutive pattern tests can be merged into a more efficient operation.
__dynamic_cast_first prototype is
implemented in libc++abi for
batching consecutive
dynamic_cast
and sharing the hierarchy traversal.
Timings at
-O2, in
nanoseconds per call:
Input
|
Without Batching
|
With Batching
|
Speedup
|
|---|---|---|---|
| Circle (first) | 4.07 | 3.48 | 1.17x |
| Triangle (middle) | 13.23 | 9.09 | 1.46x |
| Rectangle (last) | 23.04 | 8.19 | 2.81x |
| Square (derived) | 28.61 | 13.03 | 2.20x |
-fexperimental-batched-dynamic-cast.using SearchResult = std::variant<File, Directory>;
bool is_file(const SearchResult& result) {
return match(result, case { const File& });
}A single-pattern test produces
bool. Its
declarations are local to the test.
using SearchResult = std::variant<File, Directory>;
SearchResult search(std::string_view path);
std::optional<File> find_file(const Directory&, std::string_view name);The declared names are available to subsequent conditions and the body.
Pattern
|
Example Forms
|
Matching Operation
|
|---|---|---|
| Value | 0,
Coin::Penny |
Compare a value |
| Predicate | is_even,
starts_with("-I") |
Invoke a callable constant |
| Wildcard | _ |
Match without introducing a name |
| Declaration | const T& xauto [x, y] |
Bind or initialize a declaration |
| Decomposition | [0, int y][P, ..., Q] |
Match structured-binding elements |
| Alternative | { P }{ T: P }{ C: P }{ .name: P }{ .name<I>: P } |
Match a state and optionally project it |
| Or-pattern | P or Q |
Try patterns against the same subject |
| Parenthesized | (P or Q) |
Group a pattern |
alternative_traits
for
std::expectedtemplate <class T, class E>
struct std::alternative_traits<std::expected<T, E>> {
static constexpr std::alternative_info alternatives[] = {^^T, ^^E};
static constexpr bool has_residual_states = false;
static constexpr std::size_t index(const std::expected<T, E>& result) noexcept {
return result.has_value() ? 0 : 1;
}
template <std::size_t I, class Self>
static constexpr decltype(auto) get(Self&& self) {
if constexpr (I == 0) return *std::forward<Self>(self);
else if constexpr (I == 1) return std::forward<Self>(self).error();
else static_assert(false);
}
};This is sufficient to support
{ P },
{ T: P }
and
{ C: P }.
alternative_traits
for
std::expectedtemplate <class T, class E>
struct std::alternative_traits<std::expected<T, E>> {
static constexpr std::alternative_info alternatives[] = {^^T, ^^E};
static constexpr bool has_residual_states = false;
enum class state { value = 0, error = 1 };
static constexpr std::size_t index(const std::expected<T, E>& result) noexcept {
return result.has_value() ? 0 : 1;
}
template <std::size_t I, class Self>
static constexpr decltype(auto) get(Self&& self) {
if constexpr (I == 0) return *std::forward<Self>(self);
else if constexpr (I == 1) return std::forward<Self>(self).error();
else static_assert(false);
}
};alternative_traits for
std::expectedtemplate <class T, class E>
struct std::alternative_traits<std::expected<T, E>> {
static constexpr std::alternative_info alternatives[] = {^^T, ^^E};
static constexpr bool has_residual_states = false;
enum class state { value = 0, error = 1 };
static constexpr state index(const std::expected<T, E>& result) noexcept {
return result.has_value() ? state::value : state::error;
}
template <std::size_t I, class Self>
static constexpr decltype(auto) get(Self&& self) {
if constexpr (I == 0) return *std::forward<Self>(self);
else if constexpr (I == 1) return std::forward<Self>(self).error();
else static_assert(false);
}
};alternative_traits for
std::expectedtemplate <class T, class E>
struct std::alternative_traits<std::expected<T, E>> {
static constexpr std::alternative_info alternatives[] = {^^T, ^^E};
static constexpr bool has_residual_states = false;
enum class state { value = 0, error = 1 };
static constexpr state index(const std::expected<T, E>& result) noexcept {
return result.has_value() ? state::value : state::error;
}
template <state State , class Self>
static constexpr decltype(auto) get(Self&& self) {
if constexpr (State == state::value) return *std::forward<Self>(self);
else if constexpr (State == state::error) return std::forward<Self>(self).error();
else static_assert(false);
}
};{ .value: P }
looks up value inside the return
type of
index(), and
the nested P matches against
get<state::value>(subject).
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);Source: JSONFormat::writeArtifact,
p2688-selfhost.
The
R.message
has 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});
}
}match (R.message) {
case { { eResponseMessageCancelled } } => Result.insert({"message", "cancelled"});
case { { eResponseMessageNotStopped } } => Result.insert({"message", "notStopped"});
case { { const String &message } } => Result.insert({"message", message});
case {} => ;
}The outer braces project the optional, and the inner braces project the variant.
Source: LLDB response serialization.
Many projects provide custom, manual runtime type information without
C++ RTTI.
We’ll use Clang/LLVM as an example.
switch (D->getKind()) {
case Decl::Function: {
use(cast<FunctionDecl>(D));
break;
}
case Decl::Var: {
use(cast<VarDecl>(D));
break;
}
}The
switch can
warn on missing enumerators, but requires the enum-to-class mapping.
Reference: How to set up LLVM-style RTTI.
An API accepts a group key as a numeric ID, a scoped name, a name, or an alias:
struct ScopedName {
1: string scope;
2: string name;
}
union GroupKey {
1: i64 id;
2: ScopedName scopedName;
3: string name;
4: string alias;
}
getType()
identifies the active field, or
Type::__EMPTY__.name and
alias both have
string payloads.Assume
alternative_traits<GroupKey>
and structured-binding opt-in for
ScopedName, generated by the Thrift
compiler.
std::string describe(const GroupKey& key) {
switch (key.getType()) {
case GroupKey::Type::id:
return std::to_string(*key.id());
case GroupKey::Type::scopedName: {
const auto& scoped = *key.scopedName();
if (scoped.scope()->empty()) return *scoped.name();
return *scoped.scope() + ":" + *scoped.name();
}
case GroupKey::Type::name:
return *key.name();
case GroupKey::Type::alias:
return "@" + *key.alias();
case GroupKey::Type::__EMPTY__:
throw std::runtime_error("empty group key");
}
}std::string describe(const GroupKey& key) {
return match (key) -> std::string {
case { .id: const auto& id } => std::to_string(id);
case { .scopedName: ["", const auto& name] } => name;
case { .scopedName: const auto& [scope, name] } => scope + ":" + name;
case { .name: const auto& name } => name;
case { .alias: const auto& alias } => "@" + alias;
case {} => throw std::runtime_error("empty group key");
};
}template <typename T>
int classify(T value) {
return match (value) {
case { int } => 0;
case { std::string } => 1;
case { char } => 2;
};
}Viability and exhaustiveness are checked for each
specialization.
Non-viable cases are discarded during instantiation.
A non-viable case is ill-formed outside a dependent context. (similar
to
if constexpr)
This addresses example #3 in P3619R1.
Upcoming for R7: Placeholder declarations introduce
a template region for the pattern, guard, and handler, including the
single known projection of
std::optional<int>.
Here,
if constexpr
discards the
size() call
for int.
struct DoSomething { void do_something(); };
void handle_bool(bool);
void handle(std::variant<bool, DoSomething> value) {
match (value) {
case { bool bit } => handle_bool(bit);
case { auto& object } => object.do_something();
}
}The generic handler is instantiated only for
DoSomething.
void handle_true();
void handle_false();
void handle(std::variant<bool, DoSomething> value) {
match (value) {
case { true } => handle_true();
case { false } => handle_false();
case { auto& object } => object.do_something();
}
}Together, the first two cases cover
bool. The
generic handler is instantiated only for
DoSomething.
int classify(bool flag) {
return match (flag) {
case bool value => value ? 1 : 0;
case true => 2; // R7: redundant-case warning
};
}
Condition
|
R6
|
R7 Draft
|
|---|---|---|
| Missing required case | Error | Error |
| Viable but redundant case | Error | Warning |
| Non-viable case in a non-dependent context | Error | Error |
int classify(const std::variant<bool, int>& value) {
return match (value) {
case { true } => 0;
case { false } => 1;
case { int } => 2;
};
}The first two cases match only the
bool
alternative. Integer values 0 and 1 reach the third case.
<=>.For an
int
subject:
case int x // viable
case const int& x // viable: binds the subject
case long x // not viable
case bool x // not viableDeclaration patterns do not accept general implicit conversions. Numeric conversions and user-defined conversions do not make a declaration pattern viable.
Assume Widget has a non-trivial
move constructor.
Move Before Testing
|
Test Before Moving
|
|---|---|
A failed guard continues matching. A non-trivial move before the guard could leave the subject in a moved-from state.
int value = 2;
auto bad_guard = [&] { value = 3; return false; };
match (value) {
case 1 => one();
case 2 if (bad_guard()) => two();
case 3 => three();
case _ => other();
}Cases have source-order priority. An implementation may test later patterns before an earlier case’s guard.
other().three().A prior dispatch decision may remain in effect after the assignment.
int classify(const std::variant<int, std::string>& value) {
return match (value) {
case { int } => 0;
case { const std::string& } => 1;
};
}Exhaustiveness covers the advertised states.
valueless_by_exception is still
possible.
LLVM StringSwitch
|
Pattern Matching
|
|---|---|
constexpr auto starts_with(StringLiteral prefix) {
return [prefix = StringRef(prefix)](auto&& text) {
return text.starts_with(prefix);
};
}Source: ARM::parseArchISA.
TrivialCopier accepts
texture-to-texture and buffer-to-buffer copies.
auto texture_input = std::get_if<OpenClTexture>(&input_obj);
auto texture_output = std::get_if<OpenClTexture>(&output_obj);
if (texture_input && texture_output) {
return Copy(*texture_input, *texture_output);
}
auto buffer_input = std::get_if<OpenClBuffer>(&input_obj);
auto buffer_output = std::get_if<OpenClBuffer>(&output_obj);
if (buffer_input && buffer_output) {
return Copy(*buffer_input, *buffer_output);
}
return absl::InvalidArgumentError("Unexpected object");match (input_obj, output_obj) {
case [{ const OpenClTexture &input }, { const OpenClTexture &output }] => {
return Copy(input, output);
}
case [{ const OpenClBuffer &input }, { const OpenClBuffer &output }] => {
return Copy(input, output);
}
case _ => {
return absl::InvalidArgumentError("Unexpected object");
}
}Each pattern matches an input/output pair and binds both objects.
State Information
|
Meaning
|
|---|---|
| Reflected type | Projectable state, including
void |
| Reflected constant | Value-selected, non-projectable state |
| Null reflection | No advertised type or value |
empty == true |
Empty state matched by
{} |
has_residual_states |
States can exist outside the advertised set |
index(subject)
must be
noexcept.get<State>(subject)
is used only when that projectable state is active.template <>
struct std::alternative_traits<std::any> {
static bool has_value(const std::any& value) noexcept;
template <class T, class Self>
static auto try_cast(Self&& self) noexcept;
template <class T, class Self>
static auto try_init(Self&& self) noexcept;
};No finite alternatives list is
advertised. A successful result supplies a typed projection through
dereferencing.
D has type
const ObjCContainerDecl*.
This hierarchy has five concrete classes, but
getKind()
still returns the full
Decl::Kind
enumeration. The generated opt-in lists those five classes.
Dispatch excerpt from
USRGenerator::VisitObjCContainerDecl:
match (*D) {
case { const ObjCInterfaceDecl& } or
{ const ObjCImplementationDecl& } => GenObjCClass(...);
case { const ObjCCategoryDecl& CD } => GenObjCCategory(...);
case { const ObjCCategoryImplDecl& CD } => GenObjCCategory(...);
case { const ObjCProtocolDecl& PD } => GenObjCProtocol(...);
}The match is exhaustive without a default. Missing a concrete class can be diagnosed even though the shared discriminator contains many unrelated kinds.
Source: USRGenerator::VisitObjCContainerDecl.
void use(int);
void use(const std::string&);
void handle(const std::variant<int, std::string>& value) {
match (value) {
case { int x } or { const std::string& x } => use(x);
}
}Both subpatterns introduce x,
with different types. The handler is instantiated separately for each
subpattern, selecting the corresponding
use overload.
short value = 42;
match (value) {
case const int& converted => use(converted); // not viable
case const short& original => use(original);
}Allowing the conversion would make the first case consume every
short,
before the reference to the original object is considered.
void use(int (&)[2]);
void process_array(int (&array)[2]) {
match (array) {
case int (&a)[2] => use(a);
// ^^^^^^^^^^ declaration pattern
}
}A following array suffix distinguishes the declaration from a functional-cast expression. The reference binds the array without decay.
void read_v1();
void read_v2();
template <int version>
void read_record() {
match constexpr (version) {
case 1 => read_v1();
case 2 => read_v2();
case _ => static_assert(false, "unsupported version");
}
}match constexpr
selects a handler through constant evaluation and discards the
unselected handlers.
switch?switch must
preserve its integral promotions and case-label rules.match
leaves the behavior of
switch
unchanged.
Context
|
Rust
|
P2688
|
|---|---|---|
| Multi-case selection | match |
Match statement or expression |
| Single-pattern test | matches! |
Match test expression |
| Conditional binding | if let,
while let |
Pattern conditions |
| Declaration binding | let,
let ... else |
Existing structured bindings |
| Function parameters | Patterns in parameters | Not proposed |
| Loop binding | Patterns in
for |
Existing structured bindings |
The proposal supports match selections, tests, and conditions. General pattern declarations can be considered separately.
In this Clang comparison,
== remains a
linear chain at
-O3. The
prototype emits an engagement test and a table lookup for
match at
-O1.
Compiler Explorer: https://godbolt.org/z/no8aPGvj1.
Continuing the Shape hierarchy
from the tour:
struct Triangle : Shape { int height = 22; };
struct Square : Rectangle {};
[[gnu::noinline]] int dispatch(const Shape& shape) {
return match (shape) {
case const Circle& circle => circle.radius();
case const Triangle& triangle => triangle.height;
case const Rectangle& rectangle => rectangle.width();
case _ => 0;
};
}Compile the same source with and without
-fexperimental-batched-dynamic-cast.
const Rectangle&
also matches a Square. The first
matching case is selected.
Median CPU time per dispatch, in nanoseconds:
Input
|
Cast Chain
|
Match
|
Batched Match
|
|---|---|---|---|
| Circle, first | 3.38 | 3.74 | 3.37 |
| Triangle, middle | 13.61 | 13.64 | 6.39 |
| Rectangle, last | 24.93 | 24.86 | 6.61 |
| Other, missing | 33.95 | 34.04 | 6.76 |
| Disk, derived Circle | 9.11 | 9.11 | 7.36 |
| Square, derived Rectangle | 40.23 | 40.43 | 7.90 |
| Mixed | 20.68 | 20.66 | 6.48 |
The dispatch microbenchmarks were recorded on October 29, 2026, at
-O3 on an
AMD EPYC host. Application performance was not measured.
bool accept(int);
int adjust_value(const std::optional<int>& value) {
return match (value) {
case { int x } if (accept(x)) => x;
case { int x } => -x;
case {} => 0;
};
}Both value cases need the same discriminator and projection. Their results can be shared across the guard.
Written cases
|
Pattern specialization + incremental usefulness
|
Required pattern, guard, and handler instantiations
|
Checked cases and coverage diagnostics
|
Decision-tree planning
|
LLVM IR
The prototype uses different data structures for coverage checking and code generation.