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

25

u/Street-Anteater1234 Sep 20 '26

I want pattern matching, I hate monads.

12

u/tim_pipperton Sep 20 '26

What does pattern matching have to do with monads? Are you saying you don’t like monads broadly, or the ergonomics of C++’s monads?

-1

u/Street-Anteater1234 Sep 21 '26

Pattern matching and monads are orthogonal. The reason I dislike monads is that they tend to make code complicated and difficult to maintain. Whenever I need a monad, I prioritize implementing the same thing without one.

10

u/tim_pipperton Sep 21 '26

How are they orthogonal? Unless rust’s match isn’t pattern matching, I don’t see how the two things are supposed to be exclusive (see matching an optional).

Also heavy disagree on making code more complicated and harder to maintain, with the easy example of std::optional. Maybe using monads where they’re not needed can cause that, but making a blanket judgement on them like that is kinda ridiculous.

2

u/sheckey Sep 21 '26

Hey let’s hear more about the monad issues please! I’m starting to “modernize” our old code using them, and I would appreciate your experienced view.

3

u/Ayjayz Sep 21 '26

Can you go into a little more detail here? As far as I'm aware, monads are an abstraction on top of things like lists and optional and io and other computing contexts, so I don't really know what it would mean to "hate" that?

3

u/adityazero Sep 20 '26

like rust style `match` ?

4

u/tialaramex Sep 22 '26

Rust's match is the flashy obvious thing pattern matching does and likely the part C++ would actually get, but there's a lot more pattern matching in Rust and in principle C++ could do more of it.

let Ok(n) = num.try_into();  // Irrefutable, we've asserted this never fails

let Ok(n) = num.try_into() else { /* Refutable, we must cope */ }

for (n, word) in [(1, "One"), (6, "Six"), (9, "Nine")] { /* again, irrefutable pattern */ }

while let Some(item) = items.pop() { /* refutable - when it doesn't match because items was empty the loop ends */ }

2

u/mcypark Sep 23 '26

huh.. does the first example actually work? you can't just "assert" this never falls, can you? irrefutability is a property of a pattern, snd I'd think that `Ok(n)` is always considered refutable

2

u/grammingoctopus Sep 23 '26

It can work when the never/! type is involved, Rust has special handling for that. It is a bit neat. Something like Result<i32, !>. https://doc.rust-lang.org/std/primitive.never.html

1

u/mcypark Sep 23 '26

Oh~ that's very interesting. Thanks!

1

u/tialaramex Sep 23 '26 edited Sep 23 '26

Ok(n) is a refutable pattern if you say, converted an i32 into a u64 because hey what if it's negative, that's not going to be OK But perhaps we're converting an i32 into an i64 and so that can't fail, there aren't any 32-bit signed integers whose value can't be expressed with a 64-bit signed integer so now Ok(n) is irrefutable.

Notice that both these functions work, but if you swap their signatures the compiler doesn't like either of them - we can't go around asserting the narrowing case will "just work" when it does not, and contrariwise we can't go around asserting we need to check for errors in the widening case, there are no errors.

https://rust.godbolt.org/z/dPebnWMsK

Edited to add: This works because Rust has actual empty types whereas C++ does not. An empty type is a type with no values. This particular TryInto implementation will have associated Error type Infallible, and Infallible is an empty type, so the compiler can see OK there can never be errors, the Ok(n) match was actually irrefutable.

1

u/mcypark Sep 23 '26

So it's like... num_try_into() changes its type based on the target, right? like, in this example:

pub fn bigger(num: i32) -> i64 {
    let Ok(n) = num.try_into();
    n
}

The i64 makes its way through n, Ok(n) through num.try_into() such that num.try_into() actually returns a Result<i64, !> type? Is that what's happening?

4

u/tialaramex Sep 23 '26

Basically. It's actually Result<i64, core::convert::Infallible> today, but in Rust 1.100 that Infallible type (which is empty) will just become an alias for ! (which is also empty) as I understand it. For our purpose they're indistinguishable but in some contexts it matters that today they're not the same type and so a future where they are the same type is desirable apparently.

-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

→ More replies (18)

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?

→ More replies (2)

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.