Pattern Matching with match and case

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

Trying out the Implementation

A Tour of P2688R6

Value Patterns

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.
  • Cases have source-order priority.
  • Every enumerator must be covered.

Value Patterns

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.
  • Cases have source-order priority.
  • Every enumerator must be covered.

Declaration Patterns

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.

Wildcard Patterns

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.

Predicate Patterns

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.

Or-patterns

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.

Decomposition

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.

Guards

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.

Multiple Subjects

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.

Alternative Patterns: Optional

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.

Alternative Patterns: Variant

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.

Alternative Patterns: Expected

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.

Alternative Patterns: Expected

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.

Alternative Patterns: Named Selectors

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.

Polymorphic Matching

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

Quick Detour: Batched Casts

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

Pattern Tests

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.

Pattern Conditions

using SearchResult = std::variant<File, Directory>;

SearchResult search(std::string_view path);
std::optional<File> find_file(const Directory&, std::string_view name);
void open_directory_at(std::string_view path) {
  if (case { const Directory& directory } = search(path)) {
    open_directory(directory);
  }
}
void open_config(std::string_view path) {
  if (case { const Directory& directory } = search(path) &&
      case { const File& file } = find_file(directory, "config.txt")) {
    open_file(file);
  }
}

The declared names are available to subsequent conditions and the body.

Pattern Vocabulary

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& x
auto [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::expected

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

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

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

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

Real Examples

Variant Dispatch

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);
return match (A) {
  case { const TUSummary &S } => writeTUSummary(S, Path);
  case { const LUSummary &S } => writeLUSummary(S, Path);
  case { const WPASuite &S } => writeWPASuite(S, Path);
};

The patterns name each alternative. Exhaustiveness checking replaces the static_assert.

Source: JSONFormat::writeArtifact, p2688-selfhost.

LLDB Response

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.

Custom RTTI

Many projects provide custom, manual runtime type information without C++ RTTI.
We’ll use Clang/LLVM as an example.

Switch and Cast

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.

Chain of Casts

if (const auto *FD = dyn_cast<FunctionDecl>(D))
  use(FD);
else if (const auto *VD = dyn_cast<VarDecl>(D))
  use(VD);

The cast chain names the classes directly, without a enum-to-class mapping, but offers no exhaustiveness check.

Pattern Matching

match (*D) {
  case { const FunctionDecl& FD } => use(&FD);
  case { const VarDecl& VD } => use(&VD);
}

Direct access to the values without casting, and exhaustiveness checking.

Reference: How to set up LLVM-style RTTI.

Facebook Thrift IDL

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.

Named Union Dispatch

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");
  };
}

Design Points

Matching Within a Template

template <typename T>
int classify(T value) {
  return match (value) {
    case { int } => 0;
    case { std::string } => 1;
    case { char } => 2;
  };
}
classify(std::variant<int, std::string>{42});
// The char case is omitted.
classify(std::variant<char, std::string>{'x'});
// The int case is omitted.

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.

Generic Cases

void use(int);
void process(std::variant<int, std::string> value) {
  match (value) {
    case { auto x } => {
      if constexpr (std::is_integral_v<decltype(x)>)
        use(x);
      else
        use(x.size()); // discarded for int
    }
  }
}
void process(std::optional<int> value) {
  match (value) {
    case { auto x } => {
      if constexpr (std::is_integral_v<decltype(x)>)
        use(x);
      else
        use(x.size()); // discarded for int
    }
    case {} => ;
  }
}

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.

Case Instantiation

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.

Coverage (R7)

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.

Diagnostics (R7)

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

Declaration vs Expression

constexpr int x = 7;

match (value) {
  case int(42)    => matched();
  case int(x)     => matched();
  case int(x + 1) => matched();
  case _         => ;
}

Each form is a functional-cast expression, whether its operand is a literal, an existing name, or a larger expression.

case int x          // declaration pattern
case int (*f)(int)  // function pointer declaration
case int (&arr)[8]  // array reference declaration

These forms introduce names. A function or array suffix allows a parenthesized declarator.

Value Compatibility (R7)

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.

  • Built-in arithmetic and enum operands use the compatibility rules of <=>.
  • These rules determine viability. Accepted operands are compared with built-in equality.

Conversions

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 viable

Declaration patterns do not accept general implicit conversions. Numeric conversions and user-defined conversions do not make a declaration pattern viable.

Moves and Guards

Assume Widget has a non-trivial move constructor.

Move Before Testing
Test Before Moving
match (std::move(value)) {
  // error: non-trivial move into owned before the guard
  case Widget owned if (owned.satisfies()) =>
    use(std::move(owned));
  case _ => fallback();
}
match (std::move(value)) {
  case Widget&& candidate if (candidate.satisfies()) =>
    use(Widget(std::move(candidate)));
  case _ => fallback();
}

A failed guard continues matching. A non-trivial move before the guard could leave the subject in a moved-from state.

Evaluation Order (R7)

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.

  • Dispatching on 1, 2, and 3 before the guard can lead to other().
  • Testing the pattern 3 after the guard can lead to three().

A prior dispatch decision may remain in effect after the assignment.

Residual States

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.

  • A wildcard is useful, but not required, for a residual state.
  • An unmatched void-yielding match falls through. A non-void match terminates.
  • Unnamed enum values can also be residual states.

Backup

String Predicates

LLVM StringSwitch
Pattern Matching
return StringSwitch<ISAKind>(Arch)
    .StartsWith("aarch64", ISAKind::AARCH64)
    .StartsWith("arm64", ISAKind::AARCH64)
    .StartsWith("thumb", ISAKind::THUMB)
    .StartsWith("arm", ISAKind::ARM)
    .Default(ISAKind::INVALID);
return match (Arch) {
  case starts_with("aarch64") => ISAKind::AARCH64;
  case starts_with("arm64") => ISAKind::AARCH64;
  case starts_with("thumb") => ISAKind::THUMB;
  case starts_with("arm") => ISAKind::ARM;
  case _ => ISAKind::INVALID;
};
constexpr auto starts_with(StringLiteral prefix) {
  return [prefix = StringRef(prefix)](auto&& text) {
    return text.starts_with(prefix);
  };
}

Source: ARM::parseArchISA.

TensorFlow Copier

TrivialCopier accepts texture-to-texture and buffer-to-buffer copies.

TensorFlow

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");

Pattern Matching

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.

Source: TensorFlow Lite TrivialCopier::Convert.

Protocol Details

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.
  • A typed state requires a compatible projection and cannot be empty.

Open Protocol

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.

Matching a Sub-hierarchy

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.

Or-pattern Bindings

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.

Reference Binding

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.

match (42) {
  case const int& value => use(value); // materializes the int
}

Reference compatibility excludes conversion-created temporaries. A prvalue of the same type can still be materialized.

Array Declarations

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.

Compile-Time Selection

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.

Why Not switch?

  • Extending switch must preserve its integral promotions and case-label rules.
  • Type selection and recursive patterns need different matching operations.
  • match leaves the behavior of switch unchanged.

Pattern Contexts

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.

Structural Dispatch

Equality Chain
Structural Matching
int with_equals(std::optional<int>& x) {
  if (x == 0) return 42;
  else if (x == 1) return 7;
  else if (x == 2) return 99;
  else if (x == 3) return -3;
  else if (x == 4) return 55;
  else if (x == 5) return 18;
  else if (x == 6) return 77;
  else if (x == 7) return 4;
  else if (x == std::nullopt) return -1;
  else return 0;
}
int with_match(std::optional<int>& x) {
  return match (x) {
    case { 0 } => 42;
    case { 1 } => 7;
    case { 2 } => 99;
    case { 3 } => -3;
    case { 4 } => 55;
    case { 5 } => 18;
    case { 6 } => 77;
    case { 7 } => 4;
    case {} => -1;
    case _ => 0;
  };
}

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.

Batched Dispatch Example

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.

Batched Results

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.

Projection Reuse

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.

  • Equivalent matching operations, including protocol calls and checked casts, may be reused even when reducing the calls changes observable side effects.
  • Predicate calls, user-defined equality, declaration initializations, and guards are evaluated per source occurrence when needed.

Checking and Lowering

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.