Extending and Simplifying C++: Thoughts on Pattern Matching using `is` and `as` - Herb Sutter

Sdílet
Vložit
  • čas přidán 4. 06. 2024
  • cppcon.org/
    github.com/CppCon/CppCon2021
    ---
    C++20 is a unique historic milestone: It's the first edition of Standard C++ that’s “D&E-complete,” with essentially all of the features Bjarne Stroustrup outlined in /The Design and Evolution of C++/ for C++’s evolution. That doesn’t mean evolution is done, however, and work continues on adding a few more important features in C++23 and beyond, including reflection and pattern matching.
    In this talk, I’ll show the C++ pattern matching libraries and language proposals we’ve considered, and present my own contribution that builds on them. My paper has two major aims: (1) to make the syntax clean and regular, and avoid inventing a little sublanguage that works only inside “inspect”; and (2) to make it generalizable so we can use it consistently throughout the language, because matching a pattern is a broadly useful feature that ideally should not be limited to “inspect” only… for example, we would love to express patterns in “if” and “requires” conditions too.
    I hope that the most important contribution is that, if we add pattern matching in a way that also provides general “match” and “extract” support throughout the language in the form of generalized “is” constraints and “as” casts, the net result is that we can actually simplify C++… yes, even as we add new features and more expressive power. How can that be simpler? By letting programmers directly express their intent where they have to express it indirectly today, by making the language more regular with fewer special cases to learn, by unifying the syntax of existing standard library features that today have a gaggle of different and divergent styles (e.g., variant, optional), and by providing one general and expressive way to use patterns cleanly throughout C++.
    ---
    Herb Sutter
    Software architect, Microsoft
    Herb is an author, designer of several Standard C++ features, and chair of the ISO C++ committee and the Standard C++ Foundation. His current interest is simplifying C++.
    ---
    Videos Filmed & Edited by Bash Films: www.BashFilms.com
    Register Now For CppCon 2022: cppcon.org/registration/
  • Věda a technologie

Komentáře • 128

  • @Versachiful
    @Versachiful Před 2 lety +31

    I love Herb's talks. He always makes me see C++ from a new perspective :)

  • @DavidKennedyAraujo
    @DavidKennedyAraujo Před 2 lety +21

    To the other ones watching this meeting: don't lose the last minutes.
    It's an excellent wisdom sample.

  • @numv2
    @numv2 Před 2 lety +37

    Wise words from Bjarne at the very end

  • @bishop3000home
    @bishop3000home Před 2 lety +17

    Alexandresku had great insights, love how he sees things through

  • @PikachuSlapping
    @PikachuSlapping Před 2 lety +20

    Love this talk! Stuff like this makes me so excited for the future of the language. I understand it may have taken us a while to get here, but I'm glad we've reached it!

    • @MrWorshipMe
      @MrWorshipMe Před 2 lety

      We haven't reached it yet... None of these are expected to ship in c++23, and all of these were talked about 5 years ago already. C++ evolves slowly by design. It's not python. I expect to see some of Sutter's proposals make it to c++29.

  • @aliancemd
    @aliancemd Před 2 lety +29

    I don't get why we are pretending and have to always use a different name, just name it "match" - it would be easier to jump between the codebases and it's more accurate to what is actually happening "pattern matching".

  • @aperson4051
    @aperson4051 Před 2 lety +86

    Just call it "match"!

    • @MrWorshipMe
      @MrWorshipMe Před 2 lety

      I use the name match for my variables frequently enough to be concerned about using it as a keyword. I have never used inspect for naming anything.

    • @petermuller608
      @petermuller608 Před 2 lety

      While I tend to agree, let's not get into bike shedding ;)

    • @Cons-Cat
      @Cons-Cat Před rokem +1

      Popular languages that have a "match" keyword use it as expressions, whereas "inspect" is a statement. The motivation behind this name difference is to reduce confusion between languages.

  • @saulth
    @saulth Před 2 lety +11

    Yay for not having to write auto everywhere like the if-else block example. Keep up the good work improving C++ 😎

  • @theRECONN
    @theRECONN Před 2 lety +3

    Haha, "C-style cast is a Mystery cast". I am gonna call it that way from now on.
    Interesting talk from Herb, as always.

  • @gongfei
    @gongfei Před 2 lety +3

    I love listening to Herb's talk !

  • @bioweapon4627
    @bioweapon4627 Před 2 lety +22

    Like the proposal, except for "inspect". Sticking to "switch" is not bad: the "=>" can mean ":" + break. And if we really need a new keyword, why not "match"? Python and Rust already have that, so it's becoming popular.

    • @fdwr
      @fdwr Před 2 lety +4

      Agreed, inappropriate verb choice for "pattern *match*ing".

  • @MindGameArcade
    @MindGameArcade Před 2 lety +2

    Great, great talk, so good to see all the community coming together, godbolt, Sean Baxter, llvm, etc.

  • @Omnifarious0
    @Omnifarious0 Před 2 lety +6

    I agree with Jason. `as` will frequently be used in contexts where the source type is unknown because it's a template.

  • @sanjaygatne1424
    @sanjaygatne1424 Před 2 lety +9

    nice talk. amazing work done by sean baxter.

    • @CppCon
      @CppCon  Před 2 lety

      Much appreciated!

  • @fdwr
    @fdwr Před 2 lety +12

    18:03 That's beautiful, simplifying multiple disparate ways of doing it with a consistent is and as.
    22:14 "auto i is int = x" Having a hard time mentally parsing this. 🤨
    I get this: (i is int)
    Or this: (auto i = x)
    But there's no placement of parentheses that makes this make sense 🙃:
    "(auto i is int) = x" What? bool = x?
    "auto (i is int) = x" Nope. auto bool = x?
    "auto i is (int = x)" Huh?
    We already have the existing "if (auto a = b; condition)". So let's find a way to be self-consistent within the language, more like "if (auto i = x; x is int) " (though, the problem here is the initialization order happens before the test :/).
    27:00 Please no. "auto [_,y] is [0,even]."
    32:08 Why doesn't variant have an intuitive straight-forward is_type() method? v.is_type() would be much clearer and more discoverable than the mouthful std::holds_alternative(). Bjarne speaking of uniformity at the end really highlights variant as the oddity in the bunch compared to optional and any. I mean, why do optional and any have has_value, but variant has this awkward interaction with monostate?
    35:21 The UFCS nay-sayers stand on flimsy arguments. I so wanted this yesterday, as did Bjarne.
    41:31 "inspect" feels like a really awkward verb. Inspect doesn't imply matching or branching. "match" or "branch" implying matching and branching. So just call it "match". The feature's name is after all "pattern matching".
    41:56 Using "=>" for this purpose, how does that play into future terse delegates? Will they cooperate nicely and both be parseable?
    45:26 Interesting that this obviates the immediately invoked function expression using lambdas to achieve switching.
    55:11 Gah, what? These "refinements" don't appear to be simplifying the language, unlike "is" and "as" which do simplify it 😯.
    1:00:17 "They are saying C++ is too complex" Yeah, so let's be careful about what we add, lest we make it considerably more complex to understand, more 18:03 and less 55:11.
    1:08:01 Speaking of cleaning up divergent syntax where we can, tuples of varying types (e.g. parameter lists in function calls) have historically been grouped together via parentheses (or angle brackets in the case of std::tuple), not square braces, which are used for arrays. So abusing [] for lambdas (C++11 mistake) and now structured bindings and now apparently pattern *match*ing is definite room for language cleanup. Alas, it's probably the operator comma inside parentheses that complicated all this.
    1:12:45 When both the creator of C++ and ISO C++ committee chair want UFCS and it still hasn't happened, then it's clearly a challenge to get through.
    1:26:45 I'm also quite happy with the explicitness of an "as" being clear enough to the compiler that I mean the cast that I mean. The warnings about double to float are just obnoxious.
    Ok, I'm glad this isn't arriving in C++23, because it still feels half baked, with part beautiful and part hideous, and I'm hoping that by C++26 it will more elegant and self-consistent.

  • @martinmckee5333
    @martinmckee5333 Před 2 lety +3

    One of the features I really loved when I learned Erlang was the pattern matching. Having some version of this in the language would be great.

  • @cppmsg
    @cppmsg Před 2 lety +38

    I would prefer switch to get more capacity rather than creating a new verb "inspect", the word I find inconsistent and confusing. The word seems so passive, and the function does what switch/case does, do we need yet another keyword that does something similar to another. The fact that I would have to look for => is not a problem for me. I enjoyed the whole talk and thanks to Herb. :)

    • @timseguine2
      @timseguine2 Před 2 lety

      In a word the problem is compatibility. You can't really implement it well in a backward compatible way.

    • @bakedbeings
      @bakedbeings Před 2 lety

      Maybe "given" instead of inspect, or "evaluate" or "pachinko" ;)
      I'd maybe agree on the second point except a) ambiguity kills new users, switch needs to mean one thing and b) the committee have C switch compatibility to consider.

    • @KhalilEstell
      @KhalilEstell Před 2 lety +1

      I think that overloading the same words over and over and over again can make the language more confusing for users. And there is still the point about C compatibility so I feel that the new keyword is justified.

    • @KhalilEstell
      @KhalilEstell Před 2 lety +1

      Also, I've never liked the word switch in programming in general, so I'm realizing I'm biased here. Like `which` or `select` makes sense. I just memorized that switch is what is used there.

    • @fdwr
      @fdwr Před 2 lety

      @@KhalilEstell Switch works for me because you think of it like a train track switch, which only follows one track. "inspect" though makes near zero sense as a verb, and @dmacmakes choice of "given" or "evaluate" make more sense. Though "match" is still my favorite given it is pattern *match*ing.

  • @kg3217
    @kg3217 Před 2 lety +12

    My take would be: either adding the functionality to `switch` or maybe use `match`, actually it makes more meaning to me, plus I think it resonates the idea of pattern matching to many having even wrote a hello world in Rust, and i think there are a lot in C++ community also :D

    • @fdwr
      @fdwr Před 2 lety +3

      Yeah, "inspect" as a verb makes little sense and sounds quite awkward. Inspect doesn't imply matching or branching. "match" or "branch" implying matching and branching. So just call it "match" - the feature's name is "pattern matching" after all.

    • @vikinggeorge7007
      @vikinggeorge7007 Před rokem +1

      I personally believe inspect makes more sense than match, because you're inspecting an element for the most part. In Rust, you can quite literally match with monadic types like Result and Option. In C++, we don't have Some() and None, or Ok() and Err(). I still prefer try except blocks for errors, because it looks a bit clearer for that specific purpose, but for std::optional we really need to have an easier way to do pattern matching, although I'm happy with .value_or().
      Pattern matching is becoming fairly decent in C++ as time goes by. It really fuels more and more passion for the language into me.

  • @VioletGiraffe
    @VioletGiraffe Před 2 lety +4

    I can't believe no one let Bjarne take their spot higher up the line when asking the questions...

  • @AG-ld6rv
    @AG-ld6rv Před 2 lety +9

    There's going to be many, many Stack Overflow questions in the future. Having powerful simplifications going forward will help people who make professional C++ code, but students will always investigate all there is out there. One of the most common question types about C++ on Stack Overflow is either directly about or silently contains something like a C-style array instead of an std::vector, std::array, or std::string. The older material will stay forever. Plus, while powerful abstractions help people comfortable with C++, they are often a source of confusion for new programmers who are trying to memorize the 8 different meanings of is or as shown in a table inside some book.

    • @nenoganchev2116
      @nenoganchev2116 Před rokem

      That's where Bjarne's "A Tour of C++" book comes in, I think. The old material will stay forever, but now that we have a relatively succinct guide on how to write modern code we might as well forget about that old stuff.

    • @lepidoptera9337
      @lepidoptera9337 Před rokem

      That is the reason why I never write C++. If I need classes, I emulate them on C with structures. It works extremely well without having to resort to the ridiculous syntax of C++. And yes, I used to do C++ all the time. I spent 90% of my time trying to figure out obscure compiler errors. It's a language that gets in the way every time it tries to "help". Only thing worse are VHDL and Verilog.

  • @alidanish6303
    @alidanish6303 Před 2 lety +2

    last 2 decades C++ was trying to stabilized and establish itself as the most important language on the planet to design and maintain mission critical evolving system. I think next decades will be very interesting and some original C++ features will be out soon

  • @oisyn-
    @oisyn- Před 2 lety +35

    Great talk. The syntax is a bit confusing though. Why "x is int", but if you want a named binding, you do "auto y is int = x"?
    "x is int y" would make more sense to me. After all, you're testing whether 'x' is int, not 'y'. Not sure what the parseability of that is though, but the proposed syntax seems very backwards and inconsistent.

    • @jhbonarius
      @jhbonarius Před 2 lety +2

      That's the way C# does it

    • @7mile929
      @7mile929 Před 2 lety +1

      ​@@jhbonarius Yes. Herb is also working for MS, I don't think he doesn't know how C# does it. Why he chose this syntax? Or it came from other collaborators?

    • @KhalilEstell
      @KhalilEstell Před 2 lety

      @@7mile929 Yes, I believe he is using the same syntax from C# to not reinvent the wheel when you don't have to. But yeah it does look strange to me. I don't really have too many complaints otherwise though.

    • @betacar0tin
      @betacar0tin Před 2 lety

      I agree, I thought the same thing.

    • @lefteriseleftheriades7381
      @lefteriseleftheriades7381 Před 2 lety

      Yes I was stumped when i tried to parse that in english. Code should read like a prose and the proposed syntax doesn't

  • @peregrin71
    @peregrin71 Před 2 lety +2

    @HerbSutter There is something left implicit, inspect will evaluate is/as in the order they are written in. Specialy clear in cases with "is _" you don't want to have that on top. Just a bit of nitpicking on syntax here, I'd rather type "default (or else)" then "is _" (default/else is intent, is "_ is" the how/implementation detail)

  • @AngeloMastroberardino
    @AngeloMastroberardino Před 2 lety +1

    Agree! That would make writing and reading C++ easier.
    A side effet would be getting the joke: "C++ be like C#"

  • @valizeth4073
    @valizeth4073 Před 2 lety +9

    I really hope this gets accepted into C++23

    • @MrWorshipMe
      @MrWorshipMe Před 2 lety

      I would also have loved it... But unfortunately, it's not planned to be included. At the pace c++ is evolving, maybe we'll see it in c++29, but don't hold your breath. Anyway, it's good to have something to look forward to.
      Maybe c++ should have a lts/stable branch and an experimental/dev branch? I guess Godbolt is kinda that, maybe we should make it work offline too.

    • @fdwr
      @fdwr Před 2 lety

      I would like half of it to be accepted, the clean half which reduces complexity and increases language consistency ("as" and "is"). The other, the pattern matching (which I'll call "match" because "inspect" is an awkward and unintuitive verb for this usage) needs more bake time. So I'm kinda glad this isn't in C++23, as 26 will give it more time to iron out the kinks.

  • @vasi1iska
    @vasi1iska Před 2 lety +2

    It really motivates

  • @SuperNolane
    @SuperNolane Před 2 lety +10

    C++98: C-style cast may have multiple different meanings so we added *_cast syntax to make programmers' intentions explicit.
    C++23: We reinvented C-style cast, but now you can even get value from optional or future with exactly the same syntax as type casting.

  • @robinmoussu
    @robinmoussu Před 2 lety +2

    As good as always!

    • @CppCon
      @CppCon  Před 2 lety +1

      Glad you think so!

  • @arisweedler4703
    @arisweedler4703 Před 2 lety +6

    When I learned about Rust’s “as” keyword, it just made so much sense. In my mind, that idea kinda defeats the need for weak_ordering.
    No need to weak_equality filepaths - just equality them as strings or equality them as file locations. If you need to make the distinction between the two valid equalities on these types then you should always unambiguously declare which one you wish to use - failure to do so should be a compiler error.
    I do believe that leaning hard on the type system creates better code. That is thought but not impossible to do in C++. Anything that makes that easier, ANYthing,,, I think that’s a win.
    There is so so much potential, and my gosh it really is a different language now than it used to be. That spooks and excited me.

    • @arisweedler4703
      @arisweedler4703 Před 2 lety +1

      One more highlight of the talk for me was 1:11:35 when he said that about the spaceship operator. It’s makes perfect sense that we don’t need to give code that returns any more than “more than”, “equal”, or “less than”! That it makes the standard smaller too... It IS that simple!

    • @arisweedler4703
      @arisweedler4703 Před 2 lety +1

      Ben Deane is so cool. I have learned a lot from him and I am thankful. 1:16:00
      And Jason Turner 1:25:53

    • @fdwr
      @fdwr Před 2 lety

      One thing unclear to me is the order of operations? If you say "animal as Mammal.Mouth", does that mean "(animal as Mammal).Mouth" or "animal as (Mammal.Mouth)", where the first casts to mammal and reads a Mouth property and the second casts Animal to a Mouth type.

  • @Cons-Cat
    @Cons-Cat Před 2 lety +3

    Wow! This is amazing!

    • @CppCon
      @CppCon  Před 2 lety

      Thank you so much!

  • @27182818284590452354
    @27182818284590452354 Před 2 lety +13

    Since "if" is already a pattern, can we have "else" instead of "is _"? Thanks.

    • @nickelpro1
      @nickelpro1 Před 2 lety +1

      Agreed, akin to haskell's "otherwise". It makes sense to use a keyword for the backstop case

    • @fdwr
      @fdwr Před 2 lety +1

      Yes, please no "_".

  • @WilhelmDrake
    @WilhelmDrake Před rokem +1

    Herb Sutter is a Canadian Nation Treasure.

  • @kg3217
    @kg3217 Před 2 lety +1

    Though I agree with the 2nd last person, I think it's adding more and more things for complexity, it kind of becoming like some ancient programs (I dont know of other language's progresses), with a baggage of the past

  • @jhbonarius
    @jhbonarius Před 2 lety +15

    Talking from the C# community: yes many people love pattern matching, but just as many hate it. In my company for instance it's not allowed to use it, as the lead engineers want to keep the coding style uniform.
    New features often seem to lead to a spilt in the community: conservatives vs progressives.

    • @brandonlewis2599
      @brandonlewis2599 Před 2 lety

      Fight the power!

    • @MrWorshipMe
      @MrWorshipMe Před 2 lety

      It just takes time to adopt new language features. And sometimes adding them to a large code base makes it less readable (unless you refactor all of it), so better add it to new projects.

    • @PixelThorn
      @PixelThorn Před 2 lety +2

      Yep, that's why I'm contemplating switching jobs from developer to researcher. I am so done discussing code standards and naming conventions and which feature we shouldn't use because opinions and why named lambdas should never be used, not even single line ones, because opinions. Seriously fuck this shit.

  • @razterizer
    @razterizer Před 2 lety

    Don't ever stop wearing aloha-shirts.
    I'm really excited about the is/as concept thingies. Although as some have pointed out (auto i is int = x) is very hard to parse as a human. It doesn't seem to rhyme with the rest of the language.
    As with everything in programming. Nothing magically becomes better and nothing is for free. Everything has a cost, just like the law of conservation of energy.

  • @rahultandon9749
    @rahultandon9749 Před 2 lety

    How can i use later versions of C++ where older versions are mentioned/recommended, e.g. VS-C++ for UNREAL ENGINE is version 14 if I am not mistaken. More generally, does a newer version compiler have an inbuilt 'version switch' or is there an unbuilt 'backward-compatibility' as WELCOME news.

  • @nrwchd
    @nrwchd Před 11 měsíci

    finally a same way to convert type to string
    instead of guessing .str() .string() .to_tring()

  • @bearwolffish
    @bearwolffish Před 5 měsíci

    Really should be match, but this is a wonderful addition, where is it?
    .. This circle compiler is brilliant.

  • @ska4dragons
    @ska4dragons Před 2 lety +1

    Where is the talk by Sean Parent referred to by the commenter at the end?

  • @peceed
    @peceed Před rokem +2

    Switch started as assembler pattern, fallthrough semantics is an advantage, the only improvement should be done by breaking by default and falling using *continue* keyword.

    • @not_ever
      @not_ever Před rokem +1

      If you change switch to break by default you're going to be breaking a lot of existing code bases.

    • @ABaumstumpf
      @ABaumstumpf Před rokem

      @@not_ever He didn't say to change the behaviour of switch now - that would have been needed to be done waaay back in time.
      But for pattern-matching NOW this would be important.

    • @yangchangjiang
      @yangchangjiang Před rokem

      One solution is to let the IDE auto complete the break for every case, unless you delete it to fall through.

  • @videojeroki
    @videojeroki Před 2 lety

    I like that.

  • @TheHamoodz
    @TheHamoodz Před 2 lety +1

    Hilarious Steve Jobs reference at 54:00

  • @kuhluhOG
    @kuhluhOG Před 2 lety +2

    1:10:39 Although this word doesn't actually exist, the pronunciation seems nearly perfect to me.

    • @goodtimesaheadmusic
      @goodtimesaheadmusic Před 2 lety

      Yes it does indeed :D

    • @tissuepaper9962
      @tissuepaper9962 Před 2 lety +2

      pretty sure he said "gestalt and weltschmerz" which are both very real German words.
      "gestalt" -> shape, form, character
      "weltschmerz" -> a sense of depression arising from the comparison of the true state of things with the ideal state of things.

  • @USGrant21st
    @USGrant21st Před 2 lety +7

    Every year I'm asking about introducing namespaces for keywords, but nobody seems to be interested. Instead we ended up with ugly keywords like co_xxx, and inevitably there will be more of those as conflicts with the existing user codebase arise.

    • @fdwr
      @fdwr Před 2 lety +3

      Interesting - never thought of that before. You could imagine a std23 namespace with the await keyword, and to consume it, just say "using std23". 🤔 I like it.

  • @qm3ster
    @qm3ster Před 2 lety +1

    what's the point of
    if (v is int) {x = v as int
    when you can just
    if (v = x as int) {
    or something like that

    • @fdwr
      @fdwr Před 2 lety

      I think he was trying to avoid an exception in the case that x couldn't be accommodated, such as with an empty optional where "as" would either explode or be undefined behavior if not tested first.

    • @Megalcristo2
      @Megalcristo2 Před 9 měsíci

      I have the same question, I guess it did so to make it more comparable with the non patter matching syntax.
      Also the actual syntax would be:
      if (auto x as int = v) {}

  • @conelatilot
    @conelatilot Před 2 lety

    What I would give to have these features available in my current work . .

  • @vikinggeorge7007
    @vikinggeorge7007 Před rokem +1

    Let's not forget easier ranges.
    auto [_, _, c] is [auto &n *= 3]{3 : 9}; // 9, 12, 15, 18, 21, 24, 27 - so c is 15

    • @314Labs
      @314Labs Před 4 měsíci

      Lovely idea! but destructing an array with more than 3 elements to 3 variables sounds like a bad idea.

  • @garyp.7501
    @garyp.7501 Před 2 lety +4

    Nice job Herb! and I don't like break;case.... but meh.
    switch(v) {
    case 1:
    fn();
    break;
    case 2:
    // fall through
    case 3:
    gn();
    }
    vs
    switch(v) {
    break case 1: fn();
    break case 2:
    case 3: gn();
    }
    I find the first easier to read.

  • @DrGreenGiant
    @DrGreenGiant Před 2 lety +2

    It's a pity that in the embedded world with no-rtti and C HALs that we are still stuck being forced to use reinterpret_cast for uint8_t buffers to/from hardware and cannot use std::variant so have to fall back to unions. I can't wait for the day when we have C++ HALs, but I genuinely don't see that happening any time soon if ever. So we are stuck with these "unsafe" and "discouraged" constructs. For me as an mid career embedded firmware engineer trying to stay up to date with best practices, then going to work and having to do something contrary, it is really demoralising.

    • @StanleyPinchak
      @StanleyPinchak Před 2 lety +2

      You can use variant and optional without RTTI or exceptions. I use both in some STM32 projects. Now don't get me started on no reinterpret cast (c style memory mapped register casts) in constexpr land.

  • @phantom_stnd
    @phantom_stnd Před 2 lety +1

    31:25 "requires requires" looks kind of goofy doesn't it?

  • @geofsawaya394
    @geofsawaya394 Před rokem

    Wow, Herb. You didn’t address Bjarne’s concerns or postpone doing so

  • @italoaugustooliveira9664
    @italoaugustooliveira9664 Před 2 lety +2

    Sad that Circle C++ is closed source, would love to use it but that's a hard no.

  • @linuxgaminginfullhd60fps10

    Some people would learn just the high level stuff without any understanding of the basis. I've already seen people misusing auto leading to extremely expensive to fix bugs. They don't know what type there should be, so they just stick auto in there and if it compiles, they consider their work complete. Python exceptionally more notorious than C++ with this type of problems that the high level languages have. Haskell in than sense is much safer and the compiler punishes those unqualified people to the extent of them giving up on programming. I would personally like to have more control over side effects and code misuse in C++. I would also like the template and type-level code being more concise. Some user defined sugar would be nice.
    There are places where templates are the answer and the types need to be derived by the compiler using few very simple rules. The type-level assignments(template using ...) are fine, but the branching(typename std::conditional::type) is horrible to read and write. Nevertheless I am glad those features are present, because just yesterday I've wrote 30 horrible lines of code and then just copy-pasted/transformed few thousands from the spec to get the job done. It took me hours instead of weeks. The type-level code in C++ is kinda hard to work with though. I like Haskell and ghc compiler because the TemplateHaskell extension allows to run arbitrary code at compile time and in the modern world there are many cases where that would be incredibly useful. That's what generic programming should be - arbitrary code to generate C++ code, not just some templates, constexprs, defines and the auto keyword.
    P.S. Only on the Haskell job from my past we didn't have our own unique in-house developed code generating tool.

  • @ChrisM541
    @ChrisM541 Před 2 lety +1

    Be careful not to over-confuse the language, folks - and that's the way it's heading. Your desire to 'protect' the existing codebase is tying you back - compilers can be modified!
    There's absolutely nothing wrong with extending (not changing!) the functionality and/or intent of an existing statement...better for everyone(!) to have 'everything under the one roof'.

  • @kaleygoode1681
    @kaleygoode1681 Před rokem

    "for cast we have many incantations"

  • @user-ge2vc3rl1n
    @user-ge2vc3rl1n Před 6 měsíci

    Herb trying to do good, I can't see why C++ committee so adamant about having ugly syntax like std::holds_alternative (which is not clear at all btw) over simpler syntax

  • @Valynification
    @Valynification Před 2 lety +7

    As if C++ is becoming more C#-like, and C# is becoming more C++-like.

    • @mac900282660
      @mac900282660 Před 2 lety +1

      Mr. Sutter is from Microsoft.

    • @simonfarre4907
      @simonfarre4907 Před 2 lety

      C++ has had these ideas for a long though. C# moves faster. I'd say C# tries to emulate C++ not the other way around

    • @MiloDC
      @MiloDC Před 2 lety

      They're both becoming more like F#. The C# team especially has been playing catch-up to F# for years, according to Don Syme himself.
      C++ is still king for performance, and obviously for manual memory management, but in every other way, F# destroys it. Soooo much better.

    • @X_Baron
      @X_Baron Před 2 lety

      Sutter's papers have a wild and very distinctive style of syntax but, now that I think of it, yes, the influence is evident. :)

  • @GCCsegmentationFault
    @GCCsegmentationFault Před 2 lety +4

    "is-as" are another overhead for the compiler. Even though, inspect syntax looks good, RBT rotate example is horrendous. Well, I don't want to see my beloved language turn into some scripting language because someone finds it "complex" or "unsafe". These "complex" and "unsafe" features makes c++ program is performant and separate professional and a rookie. The committee should consider these proposals to "make C++ less complex".

    • @amayesingnathan
      @amayesingnathan Před rokem

      But c++ operates under the zero overhead abstraction principle. So whilst it might cause more overhead for the compiler at compile time, it should result in exactly the same runtime result whilst producing more expressive readable code, which is arguably what actually matters.

  • @qm3ster
    @qm3ster Před 2 lety +1

    really, you can't do "is 1 | 2 | 10 || is perfect_square"? :O

  • @von_nobody
    @von_nobody Před 2 lety +3

    We have effective UFCS: `auto foo_call(auto x) { if constexpr (require { x.foo() }) { return x.foo(); } else { return foo(x); } }`, it verbose and require helper function for each function you want use.

  • @FloodAnxiety
    @FloodAnxiety Před 2 lety +3

    There are many projects that don't want to pay the cost of RTTI. I have literally never worked in a code base that had RTTI on. If RTTI is off, what does "x is Derived" and "x as Derived" going to do? Compile time error? Will turning off RTTI force people into using the old syntax?
    My favorite part of this talk was the switch details. I always suspected/hoped that is how switches were optimized and have always worried that I should be rolling my own jump tables to be sure that is what I was getting (casually inspecting the assembly generated for a function in a large project tends to discourage confirming things at times). What I want is a special switch keyword that will only ever result in a jump table and give me a warning/error if it cannot produce a jump table for my switch statement. A large switch in a tight loop could be branch prediction hell or it could be lightning fast if it is in a jump table, and I'd like to be able to express my intent at more than just the semantic level, I want to express my intent at the algorithmic level that impacts the hardware.

  • @piotrarturklos
    @piotrarturklos Před 2 lety +3

    Features, features, more features. This is great, but the hard part is getting this to work with all the other language features. Don't we have like a 100 things that this needs to work with, like constexpr volatile coroutine-generated objects on the right hand side of the "is" expression, just to give a dumb example?
    Seriously, just name some random combination of features that can affect types and see if this works with them correctly (also without accidentally adding potential for writing buggy code). Just using the new feature as intended is not enough of a test in a language as complex as C++.

    • @dennisrkb
      @dennisrkb Před 2 lety +1

      C++ is becoming a bastardized language, like C#. Soon it'll loose its idiomatic style.

  • @ABaumstumpf
    @ABaumstumpf Před rokem

    The committee see to become more and more the ivory-tower that must be avoided. The fallthrough-behaviour is one of the most important features of the switch-statement. It allows us to write more concise code and reduce code-duplication and mental gymnastic. But it is same as with many of the older constructs that some of their behaviour just make them harder to use then they should be.
    Instead of not including one of the most useful features (that then would be grandfathered in with much pain a couple versions later) it would be way simpler to have the behaviour in a configurable way.
    As an example - why not a specifier after the expression? "explicit fallthrough" - would make it clear that only by explicitly writing a fallthrough-keyword (or attribute or whatnot) would a pattern exhibit fallthrough behaviour. and "default fallthrough" would do the opposite.
    having a new keyword ... not sure if that is really helpful.
    Yes - "having to scan through" makes it sound bad, but that is not really the case. It would STILL be a switch-statement but with some other restrictions and liberties, but fundamentally it IS a "switch". Heck, by sticking with "switch" and ":" one could easily enhance switch by ADDING "=>" to the syntax and making it denote a none-fallthrough case.
    std:.string name = /*...*/;
    switch(name){
    case "Dave": case "David": case "Davie" => std::cout std::cout

    • @pizzawithpineappleissuperi4377
      @pizzawithpineappleissuperi4377 Před rokem

      For the explicit fall through continue would be a good fit as it is the "opposite" of break and isn't used so far in switch and it also avoids introducing yet another new keyword

    • @nicktreleaven4119
      @nicktreleaven4119 Před 7 měsíci

      @@pizzawithpineappleissuperi4377 but the switch may be inside a loop so continue already has meaning.
      In D we use `goto case` (with an optional expression) or `goto default`.

  • @destiny_02
    @destiny_02 Před 2 lety +1

    9:38 I don't like the fact that this syntax is promoting brace-on-current-line style and would look horrible with brace-on-next-line

  • @JohnWilliams-gy5yc
    @JohnWilliams-gy5yc Před 2 lety +1

    inspect keyword: Exists.
    c#: Oh, come on!
    c++ user: I have to pay only what I only use even if it's compile time cpu-cycle overhead. 🤷🏻
    Please please consider fixing this. I just don't see any down sides with the polymorphic switch keyword.

  • @Zanozus
    @Zanozus Před 2 lety +2

    Too much syntactic sugar. Cpp turns into Chinese.
    Please, give us more tools for multithreading, async operations and low level hardware handling.

  • @pedromiguelareias
    @pedromiguelareias Před 2 lety

    Not clear at all. Herb Sutter is a little confusing.

  • @michalmarszaleck
    @michalmarszaleck Před 2 lety +1

    This proposal is so bad. Generic programing is not about knowing type. It is about not knowing it. We do thinks for base class and we should not know what child is this class. If we need know if this is int or float we now have if constexpr and it works.
    If you want sever switch then simply propose that [[fallthrough]] is always needed when you want it.

  • @MiloDC
    @MiloDC Před 2 lety +1

    Every language wants to be F#.

    • @frydac
      @frydac Před 2 lety +9

      In every language community everyone is always referring to how F# does it right and they should strive to be more like it! I guess that is why it is the most popular and widespread language in existence, especially for systems programming

  • @bobweiram6321
    @bobweiram6321 Před 2 lety

    If it wasn't for high frequency trading, C++ wouldn't be as relevant as it is today.

  • @736939
    @736939 Před 2 lety +1

    C++ becomes the ugliest programming language ever. Linus Torvalds was right when he said that "nothing is better than C". If you want to be more productive, learn Rust. RIP C++ :(

  • @think2086
    @think2086 Před 2 lety +1

    Instead of "inspect," consider calling it "select." That would be more intuitive/consistent with other languages. The syntax is also super wonky. I understand why you did it but think you are mistaken. You are throwing SYNTACTIC LOGIC out the window, making everything just gobbledygook. There's no syntactic intuition left.
    For example, `if(auto i is int = x)` is clearly there to prevent having to do `if(x is int) { auto i = x; ...}` and similar for the others.
    THIS IS BEING TOO CLEVER. We have been warned so many times not to be too clever. It makes code ugly and exactly why people don't want to learn C++. Little mental models of syntax that are logical/intuitive are the best asset to making a language teachable, learnable, and desirable. And we are failing this because somehow we think shaving a line or two (or a subline) is worth it?
    I'd rather take the slightly less compact code for SANITY any day. Reconsider!
    Just trying to parse the chain of values/types is so painful. And it is corrupting C++ away from the beauty of the logic of syntax of C's best bits. Without good reason.
    Even in the more complex cases like structured binding, I'd just rather have `inspect(x is [int, int, bool]){ auto [a, b, flag] = x; ... }` than `inspect(auto [a, b. flag] is [int, int, bool] = x)`. It's much clearer, and I gain almost nothing by going with CRAZY CODE.
    I wonder whether this is what Andrei meant about "lighter weight syntax." It seems like you're trying to do too much and f'ing up the syntactical logic in the process, making C++ EVEN weirder.
    For inspect, the more sane "lighter-weight" syntax would look like this:
    `inspect(x) { `
    ` is int => {/* stuff */} `
    ` is integral => {/* stuff */} `
    ` is [int, int] => {auto [a, b] = x; /* stuff */} `
    ` is [int, int, int] => {auto [a, b, c] = x; /* stuff */} `
    ` is [0, even] => { auto [_, y] = x; /* stuff */} `
    ` is string => { auto s = x as string; /* stuff */} `
    ` default => {/* stuff */} `
    ` }
    Of course, I would suggest changing it to `select(x)` instead of `inspect(x)`.
    But the point is, please don't try to smoosh things together into a bizarre, unintuitive syntax!
    SIDE NOTE about structured binding syntax: it would be nice if we could do [ , y] = x; where leaving an element in a structured binding empty ignores it. This would avoid silly tricks like discarding variable names and using _ and ___ and ____, etc. in structured bindings in general throughout the language, which is U.B. You use `_` in two very different ways here which is very problematic: both as a discard-variable name in a structured binding, and as a "type wildcard" for "none of the above TYPES." That seems prone to issues. So here I used `'default` instead for the latter. No `is` statement needed or warranted here IMO. However, I do want to be able to do stuff like:
    `inspect(x){ `
    ` is [ , , bool] => {/* stuff */} // x is a 3-tuple of any types up to the last one, which is bool `
    ` is [ , , , ..., float] => {/* stuff */} // x is a n-tuple of any types up to the last one, which is float `
    ` is int; is bool => {/* stuff */} // x is an int or x is a bool `
    ` is integral && std::less => {/* stuff */} // x is of an integral type and less than 100 `
    `} `
    As for the point about lossy is/as, consider `~is` and `~as`. ~ would mean "equivalent, potentially modulus any narrowing/lossy conversions including implicit ones." You could even have +as and +is to mean "exactly matches." (No conversions at all--even if provided.) Then `as` and `is` by themselves would mean the happy middle ground: "no implicit, compiler-provided narrowing or lossy conversions, but other user-provided conversions allowed."
    @37:42 I don't understand the variant code at all. I would have thought it should be like
    `template constexpr auto operator is( std::variant const& x)
    { return x.holds_variant(x); }`
    and
    `template constexpr auto operator as( std::variant const& x) -> auto&&
    { return std:::get(x); }`
    Instead, you ignore the types asked for and the corresponding type versions of std::variant methods, and work with indices??? All I can think is that you've added some magic to convert types to indices behind the scenes for variant-like types? What gives?