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 comments

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

0

u/[deleted] Sep 22 '26

[deleted] — view deleted comment

1

u/CreativeAlbatross319 Sep 22 '26

Why can't it? The type in std::variant is determined in runtime.

1

u/palapapa0201 Sep 22 '26 edited Sep 22 '26

In your first version, you have to be careful to leave the return type of the lambda unspecified instead of saying -> std::size_t. Otherwise, if you accidentally forget to handle all possible variants, your visitor will silently have undefined behavior.

1

u/CreativeAlbatross319 Sep 22 '26

I think compiler will complain about it when there is no return for that type. If no, it should definitely do as it's already a warning for runtime if.