C++ Logo

std-discussion

Advanced search

Proposal for switch statement extension

From: Jefferson Carpenter <jeffersoncarpenter2_at_[hidden]>
Date: Thu, 10 Sep 2026 14:05:10 -0500
Hi all,

I'd like to propose some "syntactic sugar" that ties the switch
statement language feature to the std::variant standard library type.
The idea is to make the process of visiting a variant much cleaner and
simpler.

Basically it has to support the following code transformation:

switch (x) { // Assume x is of type std::variant<MyClass, int>
case (MyClass myclass): { a(myclass); break; }
case (int n): { b(n); break; }
}

to the following:

struct Unnamed {
  void operator()(MyClass const& myclass) { a(myclass); }
  void operator()(int const& n) { b(n); }
};
Unnamed{}(x);

so that the code jumped to from each case is transformed into a
function call operator overload. A braced-enclosed code block ending
in a break statement may be required after each case "label" even when
there are no variables declared in the body or if fallthrough were
desired so that the code that must be moved is outlined and easy to
move.

This could potentially be extended to other non-std::variant types if
there were a mechanism like std::get, but I haven't explored this at
all.


This would be very useful to me, as I've written a lot of
programming-language-like programs and use std::variant extensively to
represent expression trees.

It would make C++ much more viable for programs like this to have the
code for visitors easier to read and type than calls to std::visit.


Warm Regards,
Jefferson Carpenter

Received on 2026-09-10 19:38:06