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.

57 Upvotes

163 comments sorted by

View all comments

Show parent comment

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.