r/cpp • • Sep 20 '26

CppCon At cppcon WG21 had a whiteboard asking attendees what they would like to have in C++29

some of the ones I remember was:

- contracts

- profiles

- delete moar stuff

I'm curious what folks here expect. Also if someone remembers rest of the list, that'd be great.

59 Upvotes

163 comments sorted by

View all comments

Show parent comment

-6

u/CreativeAlbatross319 Sep 20 '26

What's wrong with current pattern matching using if constexpr and concepts? It can achieve the same without any new features or keywords.

8

u/adityazero Sep 21 '26

`if constexpr` and concepts are only compile time. Pattern matching in C++ are usually achieved by switch statement, or virtual methods (with type erasure), or the classical visitor patterns. In functional languages one can write a `match` that visits each block based on whether the LHS of the pattern is a match. It is quite powerful and saves a ton of boilerplate code.

2

u/CreativeAlbatross319 Sep 21 '26

But is this pattern only runtime? If not, compile time pattern matching can be transformed into runtime with std::visit.

10

u/palapapa0201 Sep 20 '26

Rust-like enums using variant

-1

u/CreativeAlbatross319 Sep 20 '26

No idea what you say.

8

u/RogerLeigh Scientific Imaging and Embedded Medical Diagnostics Sep 21 '26

Look at how enums work in the Rust language. Conceptually similar to std::variant, with a powerful match operator to handle the different cases, checked at compile-time. C++ has nothing like it. You can kind of do the matching based upon the variant type only, as operator() overloads with visit() but it's far clunkier and far less readable. It's specialised by type, not by pattern matching.

-6

u/CreativeAlbatross319 Sep 21 '26

Please explain the problem in C++ or C. I don't care what Zig, or Go, or Carbon, or Rust is doing.

10

u/KuHeT Sep 21 '26

The point is to find some good thing present in other languages
It’s crucial to see the world wider and to see what the other languages offer

→ More replies (1)

4

u/RogerLeigh Scientific Imaging and Embedded Medical Diagnostics Sep 22 '26

That kind of attitude is rather self-limiting. It's making the assumption that it's even possible to express the concept in C or C++, and that these languages have everything they need.

They don't. Other languages can and do have interesting and unique features which can be very useful. And some of them can't be expressed directly in C or C++; they are sufficiently different that the concept doesn't carry over, unless you modify the language. "match" is once such concept.

I might be a C++ programmer for the most part, but I still make the effort to be aware of the capabilities and changes in other languges. Often some concepts do carry over and are worth picking up. Thinks like rust Result which can translate to std::expected. But even there, C++ lacks the language constructs to utilise them ergonomically.

1

u/CreativeAlbatross319 Sep 22 '26

See my other comment. I would rather prefer identifying the problem first, instead of considering what other languages are doing.

For example, I feel constexpr or concepts are useful in C++. Should Zig for example have this exactly same features? Probably not, as Zig has its own compile-time systems, which can achieve the same thing. "C++ has this so Zig must have this idea" isn't very good idea.

1

u/DivideSensitive Sep 24 '26

I feel constexpr or concepts are useful in C++

Ah yes, a clearly identified and pragmatic real-world problem that is a solid basis for a feeling-less discussion.

1

u/CreativeAlbatross319 Sep 24 '26

I use "feel" to indicate opinions instead of facts. There would be no discussion at all if anyone considers his opinions as facts. At least I don't want to participate in such a kind of discussion.

3

u/palapapa0201 Sep 21 '26

Basically more readable, more powerful and less verbose std::visit

0

u/CreativeAlbatross319 Sep 21 '26

How so?

6

u/steveklabnik1 Sep 21 '26

Warning: I'm much better at Rust than C++, so there might be small mistakes here.

Here's a small example of the differences. Let's say you've got a little protocol, and you want to know the size of the messages.

Using std::variant might look something like this:

#include <cstddef>
#include <cstdint>
#include <string>
#include <variant>
#include <vector>

struct Ping {};
struct Text { std::string text; };
struct Binary { std::vector<std::uint8_t> bytes; };

using Message = std::variant<Ping, Text, Binary>;

// Reusable helper to combine lambdas into an overload set.
template<class... Fs>
struct overloaded : Fs... {
    using Fs::operator()...;
};

std::size_t payload_size(const Message& message) {
    return std::visit<std::size_t>(overloaded{
        [](const Ping&) { return 0; },
        [](const Text& m) { return m.text.size(); },
        [](const Binary& m) { return m.bytes.size(); }
    }, message);
}

Rust lets you write this:

enum Message {
    Ping,
    Text(String),
    Binary(Vec<u8>),
}

fn payload_size(message: &Message) -> usize {
    match message {
        Message::Ping => 0,
        Message::Text(text) => text.len(),
        Message::Binary(bytes) => bytes.len(),
    }
}

There's a lot less ceremony going on here. This is largely because this feature is a language construct, built into Rust, whereas std::variant is, in my understanding, entirely a library feature.

There's a lot more going on with all of the details of both features, but it's used in Rust code quite heavily.

0

u/CreativeAlbatross319 Sep 21 '26

That's exactly what I meant. We already have pattern matching with if constexpr and concepts.

auto payload_size(const Message& message) -> std::size_t {
    return message.visit([]<typename T>(const T& message) {
        if constexpr (std::same_as<T, Ping>) {
            return 0UZ;
        } else if constexpr (std::same_as<T, Text>) {
            return message.text.size();
        } else if constexpr (std::same_as<T, Binary>) {
            return message.bytes.size();
        }
    });
}

If you don't use C++26, just use std::visit instead. The code can be even simpler:

struct Ping {};
using Text = std::string;
using Binary = std::vector<std::uint8_t>;

using Message = std::variant<Ping, Text, Binary>;
auto payload_size(const Message& message) -> std::size_t {
    return message.visit([]<typename T>(const T& message) {
        if constexpr (std::same_as<T, Ping>) { return 0UZ; } 
        else { return message.size(); }
    });
}

You now understand why I said we already have very good pattern matching? It's using the same tools without those useless fancy new keywords. Everything comes naturally for C++.

→ More replies (5)

1

u/ts826848 Sep 20 '26

I think you might be thinking of something else? Pattern matching is a runtime operation so I don't think if constexpr would help and while you can use concepts in a std::visit visitor that does not get you the full generality of pattern matching.

But in any case pattern matching is sort of like a combination of switch and std::visit on steroids. switch and std::visit are compare to pattern matching for simpler uses (albeit at an ergonomic cost for the latter), but neither is particularly great at more complex cases like deconstructing nested data types or cases where guard clauses might be handy.

Pattern matching pairs particularly well with variants, and it would go a long way to making std::variant less of a pain to use.

Rust's enums/match are a good example, though both features have a long lineage in other functional languages like MLs and Haskell.

I think P2688 is the current pattern matching proposal? Not entirely sure what to make of the GitHub issue

2

u/CreativeAlbatross319 Sep 20 '26

No, I meant pattern matching with concepts. I usually give std::visit a lambda temple. Inside the lambda, I use if constexpr with concepts to have different runtime code according to the properties of the type. It can be really complex as concepts can represent complex constraints.

Have you ever tried to do this?

3

u/ts826848 Sep 20 '26

Oh, I see what you mean. I'm used to the overloaded {} method of writing visitors I admittedly forgot you can also use if constexpr.

That being said, I don't think the pattern matching you describe is quite comparable? For instance, "real" pattern matching can match runtime values, while if constexpr can't. Deconstructing nested types/values is another thing that pattern matching makes significantly more ergonomic than std::visit. Pattern matching also handles variants with multiples of the same type quite well, though I want to say that's in no small part due to languages with pattern matching also tending to have named variants and anonymous tuples, both of which C++ lacks.

Maybe an example would work better? One interesting example that has stuck with me is tree manipulations. Consider this OCaml tree definition:

type color = Red | Black
type 'a rbtree = Leaf | Node of color * 'a * 'a rbtree * 'a rbtree

Which I think is approximately this C++:

enum class color { red; black; };

struct leaf {};

template<typename T>
struct node;

template<typename T>
using rbtree = std::variant<leaf, node<T>>;

template<typename T>
struct node {
    color c;
    T value;
    std::unique_ptr<rbtree<T>> left;
    std::unique_ptr<rbtree<T>> right;
};

Given an unbalanced subtree after an insertion, where B/R are colors, x/y/z are values, and a/b/c/d are other rbtree instances:

       1             2             3             4

       Bz            Bz            Bx            Bx
      / \           / \           / \           / \
     Ry  d         Rx  d         a   Rz        a   Ry
    /  \          / \               /  \          /  \
 [Rx]  c         a  [Ry]          [Ry]  d        b   [Rz]
 /  \               /  \          / \                /  \
a    b             b    c        b   c              c    d

You want this:

     Ry
    /  \
  Bx    Bz
 / \   / \
a   b c   d

OCaml lets you rebalance the subtree quite neatly using pattern matching:

let balance = function
  | Black, z, Node (Red, y, Node (Red, x, a, b), c), d
  | Black, z, Node (Red, x, a, Node (Red, y, b, c)), d
  | Black, x, a, Node (Red, z, Node (Red, y, b, c), d)
  | Black, x, a, Node (Red, y, b, Node (Red, z, c, d)) ->
    Node (Red, y, Node (Black, x, a, b), Node (Black, z, c, d))
  | a, b, c, d -> Node (a, b, c, d)

(There's more work to be done to finish the insertion, but that's beyond the scope of this example)

How would you express the same operation in current C++?

1

u/CreativeAlbatross319 Sep 20 '26

I have never implemented a RB tree myself. But I think the same principle can apply here using lambda template and if constexpr. So inside the template, you can write two different runtime paths for two types via std::same_as concept. Maybe I misunderstood your example but I believe nothing is impossible if you use C++.

4

u/ts826848 Sep 21 '26

So inside the template, you can write two different runtime paths for two types via std::same_as concept.

You can, but at that point you're basically implementing the decision tree by hand and that does not seem not particularly fun to me (I didn't go with std::visits since I didn't feel like figuring out how to correctly extract bindings, but I'm sure there is technically some way to do so; feel free to show me up):

node<char> balance(node<char> n) {
    if (n.c == color::black) {
        // If left child is a red node
        if (auto* left_1 = std::get_if<node<char>>(&*n.left); left_1 != nullptr && left_1->c == color::red) {
            // Case 1 or 2
            // If left child is a red node
            if (auto* left_2 = std::get_if<node<char>>(&*left_1->left); left_2 != nullptr && left_2->c == color::red) {
                // Case 1
                return node<char> {
                    color::red,
                    left_1->value,
                    std::make_unique<rbtree<char>>(node<char>{
                        color::black,
                        left_2->value,
                        std::move(left_2->left),
                        std::move(left_2->right)
                    }),
                    std::make_unique<rbtree<char>>(node<char>{
                        color::black,
                        n.value,
                        std::move(left_1->right),
                        std::move(n.right)
                    })
                };
            // If right child is a red node
            } else if (auto* right_2 = std::get_if<node<char>>(&*left_1->right); right_2 != nullptr && right_2->c == color::red) {
                // Case 2
                return node<char> {
                    color::red,
                    right_2->value,
                    std::make_unique<rbtree<char>>(node<char>{
                        color::black,
                        left_1->value,
                        std::move(left_1->left),
                        std::move(right_2->left)
                    }),
                    std::make_unique<rbtree<char>>(node<char>{
                        color::black,
                        n.value,
                        std::move(right_2->right),
                        std::move(n.right)
                    })
                };
            }
        } else {
            // Case 3 or 4
            // Exercise for the reader
        }
    } else {
        // Case 5
        return n;
    }
}

Granted, OCaml's GC helps with some of the boilerplate, but even if you disregard memory management I'm sure you can see that this is not nearly as convenient and/or readable (which is why I'd imagine actual RB tree implementations in imperative languages would go with a different implementation strategy assuming you even use an RB tree in the first place).

What's more, compilers can check patterns for completeness at compile time and can even tell you what pattern(s) you're missing. For instance, if you leave off the fallback case in the OCaml function you get this message from the compiler:

Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Black, _, Node (Red, _, Node (Black, _, _, _), Node (Black, _, _, _)),
Node (Red, _, Node (Black, _, _, _), Node (Black, _, _, _)))

but I believe nothing is impossible if you use C++.

Perhaps, but there's a very wide gulf between "possible" and "convenient".

1

u/CreativeAlbatross319 Sep 21 '26

Sorry, I really can't understand the problem by taking an example of RB tree implementation. Maybe you could use shapes to demonstrate the problem?

3

u/ts826848 Sep 22 '26 edited Sep 22 '26

Hrm, I'm not sure shapes will be conducive to a realistic example, but I can try.

Say you writing some kind of game where you need to chain colored shapes. Pattern matching lets you define a function to get a scoring multiplier in a fairly intuitive way:

type color = Red | Green | Blue
type shape = Triangle | Square | Circle
type shape_chain =
  | Leaf
  | Shape of color * shape * shape_chain

let multiplier = function
  (* Zero-length chain gets a score of 0 *)
  | Leaf -> 0
  (* Single shape gets base score *)
  | Shape (_, _, Leaf) -> 1
  (* Shapes with matching colors get 4x score *)
  | Shape (c1, _, Shape (c2, _, Leaf)) when c1 = c2 -> 4
  (* If the colors don't match, matching shapes gets a 3x score *)
  | Shape (_, s1, Shape (_, s2, Leaf)) when s1 = s2 -> 3
  (* Specifically getting a red triangle then a green square then a blue circle gets 10x points *)
  | Shape (Red, Triangle, Shape (Green, Square, Shape (Blue, Circle, Leaf))) -> 10
  (* Other cases are ignored for now *)
  | _ -> 0

Or to build on /u/steveklabnik1's example, maybe you are trying to extract the payload from some cursed format. Pattern matching lets you perform such extraction in a fairly declarative manner:

enum Message<'a> {
    Ping,
    Text(&'a str),
    Binary(&'a [u8]),
    Mixed(&'a [u8], Option<&'a [u8]>),
}

fn payload_size<'a>(message: &'a Message) -> &'a [u8] {
    match message {
        // Pings have no payload
        Message::Ping => &[],
        // If the text is 128 bytes, that is the payload
        Message::Text(text) if text.len() == 128 => text.as_bytes(),
        // The payload for any other text is the first 64 bytes
        Message::Text(text) => &text.as_bytes()[..64],
        // Payload for binary messages with 0xFF as the second byte and 0xABCD as the 5/6th byte
        // is everything after the 8th byte
        Message::Binary([_, 0xFF, _, _, 0xAB, 0xCD, _, _, payload @ ..])
        // Payload for binary messages starting with 0x00AB and ending with 0xFF are the other bytes
        | Message::Binary([0x00, 0xAB, payload @ .., 0xFF]) => payload,
        // Otherwise the entire binary message is the payload
        Message::Binary(payload) => payload,
        // If the header starts with 0xFEEF and there is no body, the payload is 0xCAFE
        Message::Mixed([0xFE, 0xEF, _, _], None)
        // If the header starts with 0xFEEF and the body is 0xBEEF 0xCAFE, the payload is also 0xCAFE
        | Message::Mixed([0xFE, 0xEF, _, _], Some([0xBE, 0xEF, 0xCA, 0xFE])) => &[0xCA, 0xFE],
        // If the header starts with  0xFEEF and the payload starts with 0xBEEF *not* followed by 0xCAFE,
        // the payload is whatever follows 0xBEEF
        Message::Mixed([0xFE, 0xEF, _, _], Some([0xBE, 0xEF, payload @ ..])) => payload,
        // If none of the above applies and there is no body, everything after the first 32 bits of the
        // header is the payload
        Message::Mixed(header, None) => &header[32..],
        // If none of the above apply, the body is the payload
        Message::Mixed(_header, Some(payload)) => payload,
    }
}

Sure, you can write something in C++ that achieves the same result, but I think such a solution would not be as understandable.

1

u/steveklabnik1 Sep 22 '26

Yeah, this is a very powerful part of pattern matching I didn't get into in my simple example.

1

u/StaticCoder Sep 21 '26

visit does the runtime dispatch, and if constexpr generates the cases to dispatch to. Interesting way to solve the issue, though it seems really a lot more annoying than your typical pattern matching syntax. Plus what I'm generally interested in (and end up doing with codegen and macros) is a complete switch on the variants (I don't use actual variant. My codebase predates that, and also I don't need value semantics; smaller variants can take less space). I don't see an obvious way to do that with if constexpr.