30 ms·
All C++20 core language features with examples
- zabzonk 6y agoMight be nice if the code examples were all compilable - this would mostly mean simply #including the relevant Standard Library headers.
- jonpalmisc 6y agoI hope one day we can get a widely adopted C and C++ package manager. The friction involved in acquiring and using dependencies with odd build systems, etc. is one of the things I dislike about the language. I’m aware on Linux things are a bit easier, but if it were as easy as “npm install skia”, etc. everywhere, I think many people would use the language more. Rust has package management, but not the ecosystem yet. On the other hand, C/C++ has the ecosystem, but no standard way to easily draw from it.
- dgellow 6y agoHave you tried vcpkg? https://github.com/Microsoft/vcpkg https://github.com/Microsoft/vcpkg It's a tool to manage C++ dependencies (using CMake), created and maintained by Microsoft. A lot of open source projects are supported (you can see part of the list here: https://github.com/microsoft/vcpkg/tree/master/ports https://github.com/microsoft/vcpkg/tree/master/ports).
- Const-me 6y agoI did, about a year ago. The usability was questionable. Their main workflow appears to be, all developers use that thing, everyone building packages from source code and using their own binaries. For large dependencies that’s a large waste of time if more than 1 person is working on the software. It’s possible to export built libraries as nuget packages, but these are tricky to consume. Another thing, these ports (where they applying patches to third party open-source code to squeeze them into vcpkg) are fragile. I remember cases when packages didn’t build, either at all, or subject to conditions (half of what I tried was broken when I only wanted release configurations).
- dgellow 6y agoI believe that's a recent development but vcpkg has decent binary caching now: https://github.com/microsoft/vcpkg/blob/master/docs/users/binarycaching.md https://github.com/microsoft/vcpkg/blob/master/docs/users/bi.... Edit: they also have an experimental support for registries since February of this year: https://github.com/microsoft/vcpkg/blob/master/docs/specifications/registries-2.md https://github.com/microsoft/vcpkg/blob/master/docs/specific...
- snarfy 6y agoWithout a standard ABI, having c++ binary packages is a huge pain, requiring multiple artifacts for every permutation of compiler, os, and platform. It's less painful today than in the past, simply due to fewer compilers, OSes, and platforms, but it is still a problem.
- Const-me 6y agoAll developers on that team used 1 compiler (VC++ 2017 at that time), one OS (Windows 10), one target platform (AMD64). Compiler/linker settings are shared across developers. I wanted vcpkg to export just the required artifacts (headers, DLLs, static libraries, and debug symbols), so only 1 person on the team (me) is wasting time building these third-party libraries. The team is remote, upload/download size needs to be reasonable.
- vlovich123 6y agoWidely adopted source code manager requires a widely adopted build system. CMake is certainly a contender but the ecosystem is too fragmented even then & you have to do a lot to try to link disparate build systems together. Also C++ is a transitive dependency hell nightmare & any attempt to solve that (like Rust has) would break every ABI out there. Given how bumpy such breakages have been in the past, I don't think there's any compiler maintainer eager for it (even MSVC has decided to largely ossify their STL runtime ABI). Conan is certainly a laudable attempt at something like this. Without access to their metrics though, it's hard to tell if they're continuing to gain meaningful traction or if their growth curve has plateaued. It's certainly not in use in any project at medium to bigger size companies I've worked at. By comparison, Cocoapods was pretty successful in the iOS ecosystem precisely because Xcode was the de facto build/project system.
- mikepurvis 6y agoI'm a longtime CMake user, but I think even within the CMake world, the solution is quite a bit more complicated than just "everything needs to be CMake", with a lot of hassles that arise when multiple generations of the tooling is involved, when you're trying to pass down transitive dependencies, when package X has a bunch of custom find modules with magic to try to locate system versions of dependencies but silently fall back to vendored ones. The higher up the stack you get, the worse and worse these problems get, with high-level packages like Tensorflow being completely intractable: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/cmake/modules https://github.com/tensorflow/tensorflow/tree/master/tensorf...
- vlovich123 6y agoYup. 100% agree. I totally overlooked the shitshow you'll have managing the different versions of CMake a build might require. Somehow Bazel manages to escape that mess. I think that might be a better foundation, but getting everyone to port to that... it's a tall ask & there's many vocal people who are against improving the build system they work with (hell, I've met many engineers who grumble and strongly prefer Makefiles).
- bregma 6y agoWe'd also need the one operating system on the one architecture. Perhaps the central planning committee can make that a goal for their next five year plan?
- mikepurvis 6y agoPython, Ruby, Node, Go, and Rust all work on multiple OSes and arches.
- bregma 6y agoPython and Ruby only work on the Python and Ruby interpreters, respectively, and those require an OS-specific way to install them. They work on multiple OSes and architectures as well as JavaScript or HTML. Go and Rust work only on a very very limited set of OSes and architectures. That's fine if you're targeting one of those, but it turns out the vast majority of computers in the world are not vanilla rice-pudding desktop systems or vanilla rice-pudding desktop systems adapted for the server room. The argument that some other tool solves a limited set of problems with your tool in a limited and limiting way is a poor one if you're trying to promote a universal solution.
- oblio 6y agoJava runs on many platforms (and billions of devices as Sun used to love to point out), yet packaging and dependency management are pretty much solved problems. Where there's a will, there's a way. In the C/C++ community there's no will. It's time they admit that to themselves and everyone else.
- bregma 6y agoJava runs only on the Java interpreter. C and C++ run on the bare metal of the CPU. Is Java modeled around a central repository of all dependencies so users can download random binaries off the internet?
- 6y ago
- pjmlp 6y agoJust like the sibling comment, I would vouch for vcpkg, although for my use cases NuGET will also do.
- oregontechninja 6y agoI've been using conan pretty easily. My biggest issue is that the recommended install method is via Python's pip
- jasode 6y ago>I hope one day we can get a widely adopted C and C++ package manager. [...] , but if it were as easy as “npm install skia”, etc. everywhere, It's not just the package manager (the command line tool) ... it's the canonical website source that the tool pulls from. C++ probably won't have a package manager with the same breadth of newer language ecosystems like npm/Nodejs and crates.io/Rust because for 20+ years C++ was developed by fragmented independent communities before a canonical repo website funded by a corporation or non-profit was created. There is no C++ institution or entity with industry-wide influence that's analogous to Joyent (Nodejs & npm) or Mozilla (Crates.io & cargo) I wrote 2 previous linked comments about this different timeline: https://news.ycombinator.com/item?id=24846012 https://news.ycombinator.com/item?id=24846012 Tldr, 2 opposite timelines happened: - C++ for 20+ years of isolated and fragmented development groups creates legacy codebases --> then decades later try to create package manager (vcpkg? Conan? cppget?) that tries to attracts those disparate groups --> thus "herding cats" is an uphill challenge - npm and crates.io exist at the beginning of language adoption allowing the ecosystem to grow around those package tools and view them as canonical
- coder543 6y agoGo has a perfectly good package manager that works with sources hosted on GitHub and other sites -- there isn't any centralized place for people to publish sources, unlike the other package managers you mentioned. Go's package manager also came years after the language became widely used, and it is now very widely adopted according to the most recent survey[0]. I think C++ could have a good, unified package management story. It would just require the major stakeholders to all care enough to make it happen, which seems to be the missing piece here. [0]: https://blog.golang.org/survey2020-results#TOC_8 https://blog.golang.org/survey2020-results#TOC_8.
- jasode 6y ago>Go's package manager also came years after the language became widely used, and it is now very widely adopted according to the most recent survey[0]. Are you talking about "pkg.go.dev" and the "go get" command? Isn't there some path dependence in the history of events that's not comparable to C++? Consider: - Go language: created by Google Inc - "go get" syntax for package download designed and created by Google Inc - "pkg.go.dev" funded by Google Inc and highlighted on "golang.org" website that's also run by Google Inc. There is no business entity or institution in the C++ world that's analogous to Google's influence for Go + golang.org + "go get" + pkg.go.dev. >It would just require the major stakeholders to all _care_ enough to make it happen, But it's easier to care if there was an influential C++ behemoth that captured everyone's mindshare to move the entire ecosystem forward. C++ has no such "industry leader" that dictates (or heavily influences) technical direction from the top down.
- bluGill 6y agoRust's package management is actually a downside to my adoption. I have a lot of C++, a home-grown package manager, and a large cmake based build system. Rust wants to replace all this, but that means shelling out to Rust's build system, which is a bit of a messy situation and means I need to learn a new build system with the language. (not hard, but another thing to learn). Our home grown package manager means we have our own local copy of everything - I have a hard requriement to be able to rebuild software for the next 15 years (there is a closet someplace with a windows XP service pack 1 PC so we can build some old software - God only knows if it will boot anymore). In the embedded space we need to support our old code for years, and you can't always upgrade to the latest.
- coder543 6y ago"cargo vendor" enables you to embed your entire dependency tree into your repo instantly, and compilation will work from that. Over half of your comment seems to have been predicated on the assumption that this either wasn't possible or wasn't easy... so I think your perceptions of Rust's package management system are more of an impediment to you than the actual package management system.
- saurik 6y agoOooo... does Rust have a good way to do this with submodules instead of copies?
- coder543 6y agoIt sounds like you're implying git submodules are actually a good thing... I think you're the first person who has implied such a thing to me before. Everyone I actually know agrees that submodules are basically never the right solution or a pleasant solution. But, to your question, no. Where would the submodules even point? The dependency source code artifacts are stored "immutably" (except for takedown notices or extreme abuse cases) on https://crates.io https://crates.io. They aren't git repos, and there's nowhere for git to point.
- fsloth 6y ago"I think many people would use the language more" C++ is considered the industry leading language in many fields. I'm not sure how many more you would want (given that those fields that don't use C++ ARE probably better served with some other language). I agree the build is painfull, but large orgs have for this reason specifically implemented build systems using nugets, conan/cmake or whatnot. In personal projects I just download the prebuilt binaries of component libraries and drag and drop them to visual studio, minimizing hassle. If you discard finesse and scalability as requirements you can actually jury rig a C++ project in a jiffy. You just need to let go of the idea that it must be "industry standard setup".
- throwaway894345 6y agoC++ used to be the industry leading language in many more fields, but it lost ground to other languages. Not a bad thing--"know thyself" and all that. But Rust seems like a credible threat to C++'s remaining niches (bury your head in the sand if you want), and C++ will need to evolve if it is to not lose further market-/mindshare. And it is evolving, as this article points out, but a huge glaring pain point in C++ development remains the build and package management tooling. The aforementioned build systems that large organizations operate aren't nearly as nice as, say, Cargo and I think a lot of greenfield projects who have to choose between cobbling together their own build tool to work with C++ and using Rust + Cargo off the shelf will choose the latter (other factors notwithstanding).
- pjmlp 6y agoI will get worried when NVidia releases CUDA-Rust, and changes their GPGPUs from C++ memory model to Rust, Microsoft decides to rewrite WinUI in Rust, Apple moves Metal from C++ into Rust, or Unreal/Unity get rewritten in Rust.
- throwaway894345 6y agoLike I said: > bury your head in the sand if you want Great chat, as always. :)
- throwaway894345 6y ago> Rust has package management, but not the ecosystem yet. On the other hand, C/C++ has the ecosystem, but no standard way to easily draw from it. I take your point, and I share your desire for a canonical, Cargo-like package manager and build tool for C++ (it's one of the reasons I pivoted out of C++ development); however, I don't think C/C++ "has the ecosystem" these days. It certainly has an ecosystem--C/C++ dominates its own niches, but there's a big world outside those niches and there aren't good packages for much of it. Meanwhile, Rust is growing like a weed both inside and outside of the C/C++ niches, and the package manager largely enables that rapid growth. Also, Rust has a good interop story for C/C++, allowing it to leverage the existing C/C++ ecosystem. Anyway, I hope this doesn't read as contrarianism--I just thought it was an interesting distinction.
- pjmlp 6y agoMost of the places where C++ doesn't have good libraries I wouldn't want to use Rust anyway, that is the domain of managed languages, GUIs, distributed computing, Web development. And for the stuff I use C++ for, COM/UWP, Android NDK, GPGPU shaders, Unreal/Unity, Rust tooling is yet WIP or requires to leave the confort of the existing C++ frameworks and IDE integrations.
- throwaway894345 6y agoI would use Rust for distributed computing and GUIs, and I wouldn't be surprised if it begins to break into the graphics/gamedev world in the next 5 years. Agreed that Rust is still immature in those areas today, but it seems to be on a pretty aggressive trajectory and it's only a matter of time before Rust begins chipping away in those domains. I did some real-time embedded development (including distributed embedded) in a past life in C and C++, and I really expect Rust to break through in that domain in a big way even though it's incredibly conservative (C++ is still the new kid on the block). It will take some time and it's never going to "kill" C or C++ in that domain (especially considering all the hardware that exists that LLVM doesn't yet target), but I think Rust will carve out a swathe of the embedded space for itself.
- 6y ago
- mackal 6y agoI actually extremely dislike language specific package managers. I'm on Linux, the packages should be in my package manager. I don't want to maintain multiple package managers. nmp is actually the worst here.
- Koshkin 6y agoGreat point. I think BSDs got this right with their ports. (Incidentally, NetBSD's pkgsrc supports Linux.)
- Ar-Curunir 6y agoThe Linux model of package management doesn't work for newer languages. In particular it is heavily reliant on dynamic linking, which tends not to work when you have (a) an unstable ABI (b) generics (c) a culture of static linking.
- beojan 6y agoIt works fine, you just ship the static libraries. With static linking your binaries won't have dependencies anyway. That's not to say the static linking craze is a good thing. We'd be far better off finding a way to dynamically link templates, so you get the security benefits of automatically updated dependencies that dynamic linking gives you.
- gowld 6y agoCode library managers don't belong inside OS package managers (because you want hermetic builds), unless maybe you have some Nix-live multi-manager that can provide many environments.
- quacker 6y ago> I actually extremely dislike language specific package managers. I'm on Linux, the packages should be in my package manager. I don't want to maintain multiple package managers. nmp is actually the worst here. As a user of software that doesn't care how it's built, sure. But system package managers are not a solution for general development with C++, or any other language. If I want to use C or C++ to create software, how do I use libraries that aren't available in a system package manager? What if I need a version of a library that's not available in my system package manager? There are answers here but they aren't good answers (build from source, using whichever of N build tools the project happens to use, or hope there are prebuilt libs hosted somewhere) Relying on system package managers to contain dependent libraries makes cross-platform development a complete PITA (more that it already is). Now you need the specific versions of all your libraries in package managers on all platforms, which is a complete non-solution for real development.
- flatline 6y agoConan is probably the flagship C++ package manager and supports multiple build systems including cmake. Nuget/vcpkg is also usable but does not come with build system integration.
- invokestatic 6y agoVcpkg has great CMake integration. Further, the model of Conan of distributing a bunch of binaries honestly seems like the wrong approach for C++ where you have to juggle all different sorts of compilers, triples, and ABIs. We use a completely custom toolchain which pretty much rules out Conan. The one annoying thing about vcpkg, though, is that all packages are described in the vcpkg source tree. There are no “repositories”. Customizing or adding custom packages requires using the somewhat annoying to use overlay system. I’d prefer some sort of hybrid between the two, with packages distributed as source code but pulled from a repository. I believe this is how Rust’s Cargo works.
- dgellow 6y agoJust to add a small detail: vcpkg also has Visual Studio integration, not only CMake. And regarding repositories, since February 2021 vcpkg has an experimental support for them. You can read the spec here: https://github.com/microsoft/vcpkg/blob/master/docs/specifications/registries-2.md https://github.com/microsoft/vcpkg/blob/master/docs/specific....
- scoutt 6y agoNo matter the implemented package manager solution, it has deal with different packages types: from a single class library (a single hpp file) up to monster libraries like ffmpeg. In the case of ffmpeg, what the package manager should do? Download the sources and all its dependencies and build from scratch? This is very difficult and time consuming. Because right now the alternative is going to the ffmpeg website, download and include the dll (and lib) or .so and a couple of .h files to your project. And that's pretty simple to me.
- DubiousPusher 6y agoIt's not that the package manager fixes the problem, it's that having 1 or maybe 2 or 3 canonical or popular package managers gets the implementer to fix the problem. The implementer, who has extensive knowledge of their own build system runs that aspect and creates a package that conforms to a universally expected output. It's an incredible difference going from C++, where you end up in the details of all kinds of repos and build systems, to something like C# with Nuget packages where it's a simple command or single click to start using someone else's code.
- scoutt 6y agoConsider that C/C++, being highly portable, has support for many platforms and architectures, including the possibility of cross-compiling. I guess if a package manages works on all those architectures and platforms, then the implementer would have to support all of them, and it's not always the main objective. Let alone if there are several package managers.
- DubiousPusher 6y ago> guess if a package manages works on all those architectures and platforms, then the implementer would have to support all of them, Other "highly portable" languages handle this by simply having the developer include a manifest of the platforms their library works for. The package manager only shows compatible packages for the targeted platform.
- 6y ago
- bjornjajayaja 6y agoI think the barrier to entry in the problem domain for C++ is much higher than something like nodejs. Installing dependencies is the least of one’s worries there. Also, how many dependencies are we talking about? Node apps have a million dependencies for, I think, stupid simple stuff that should just be reinvented in a given codebase. In a C++ app too many dependencies invites incompatible stylistic choices which I think will turn to a Frankenstein codebase. In Go this isn’t a problem because of “go fmt” plus a simple language at its core.
- gspr 6y agoSeems weird to have a language fill in the deficiencies of OSes wrt package management.
- botto 6y agoI'm curious if these new additions to C++ have genuine use cases (as in we could not do this because X) or if there are more academic driven arguments going on here. Having recently done a lot of work using C++ previously coming from Go and Typescript I find it hard to understand all the reasons for the language to be so flexible.
- zabzonk 6y agoMost of the language additions are aimed at library designers and writers, where they can give significant performance and ease-of-use improvements, rather than at C++ application developers.
- jackosdev 6y agoI don't see any mention of std::format, it's great for app developers, I don't think any compilers support it yet though. It's pretty much just the fmt package that you can use now.
- pjmlp 6y agoNot really, it is a subset of fmt.
- zabzonk 6y agoIt's a library addition, not a language addition.
- colejohnson66 6y agoWell, yes, but it was added in the C++ standard. I guess the standard covers the language and the library, but to me, the standard library is part of the language.
- jcelerier 6y agoit's part of the language, but not of the core language
- stefanchrobot 6y agoOh, wow. The language was complex already and this makes me avoid C++ unless it's constrained to a narrow subset (something like Google C++ Style Guide). No wonder languages like Go and Rust gain so much traction.
- zabzonk 6y agoWell, hopefully NOT like the Google Style Guide, which is pretty universally seen in the C++ community as A Bad Thing, unless you work for Google. And as I pointed out in another comment, these additions are mostly not aimed at C++ application developers. If you don't need them (and you probably won't) then don't use them.
- vamega 6y agoDo you have any pointers to information as to why it’s considered the Google style guide is considered to be a bad thing?
- pjmlp 6y agoMany of the rules that are considered best practices in Tour of C++ or C++ Core Guidelines are no go for Google.
- zabzonk 6y agohttps://news.ycombinator.com/item?id=18555771 https://news.ycombinator.com/item?id=18555771
- gumby 6y agoIt's the style guide for Google's specific environment. If you are not Google, much of it is likely irrelevant. For example, the style guide says that C++ exceptions are the way to go...except that by the time the guide was written there was already too much existing code that wasn't exception safe. Therefore the guide says that regretfully, exceptions cannot be used. Edit: clarification
- 6y ago
- steerablesafe 6y ago> However, `g_s` violates ODR because despite that there’s only one definition of it, there are still multiple declarations which are different because there are two different lambdas in a.cpp and b.cpp, thus, S has different non-type template argument. Doesn't https://eel.is/c++draft/basic.def.odr#13.10 https://eel.is/c++draft/basic.def.odr#13.10 apply here? This would make it not an ODR violation, although I wonder if compilers implement this in this specific case. I agree with the message though, lambda expressions in unevaluated contexts open new interesting ways for ODR violations.
- MauranKilom 6y agoIt's definition vs declaration: > In each such definition > However, g_s violates ODR because despite that there’s only one definition of it, there are still multiple declarations
- chris_wot 6y agoSo the requires statement just helps the class enforce certain operations? Like for instance, the class Button would need to implement the void Start(); function?
- sesuximo 6y agoI think requires/concepts do a few things: - document an interface (without making you use virtual fns or any weird tricks) - allow you to use SFINAE without more weird tricks So yeah, this amounts to enforcing that your class can do certain things... but that’s hugely helpful!
- bluGill 6y agoNot exactly - it was already enforced in C++98. The problem the enforcement was thousands of lines of compile error messages none which said anything remotely like "you didn't implement a Start function". With concepts you skip those lines that need an expert to read (and even they take a while to figure out what the error is really trying to say), and just put in a clear message.
- nsajko 6y agoI see it like this: requires can enforce any constraints (any logical predicate/boolean expression) that are able to be checked at compilation time / template instantiation time. So, you can use requires to check other stuff than if certain operations exist, like e.g.: * that a certain non-type template parameter belongs to a set of hard-coded values * that a certain non-type template parameter is an even number * constrain the number of elements in a parameter pack * things involving sizeof * that a certain non-type template parameter has a popcount of one (i.e., it only has a single bit) * that a certain type template parameter is integral AND unsigned * ...
- notum 6y agoDo [[likely]] and [[unlikely]] flags have anything to do with CPU code prediction / speculative execution that has been a burning subject recently (Spectre)?
- secondcoming 6y agoNot really. They're hints to the complier about how to order the code for 'if..else' statements.
- chrisseaton 6y ago> They're hints to the complier about how to order the code for 'if..else' statements. It's more than that - it can inform many optimisations, for example keeping values alive in one branch at the expense of another.
- sesuximo 6y agoNot really.. in part 1 of a hypothetical spectre attack, you’d have to figure out how to time a branch hit/miss, and the presence of likely may change the times/inputs you’d need to use to do that. These attributes are just hints to move hot/slow code near/far away and to maybe to the right thing if there’s no branch prediction. They cannot prevent speculative execution.
- t-vi 6y agoNot directly. It signals that the compiler does well when optimizing the [[likely]] path at the expense of making the other paths less optimized.
- secondcoming 6y agoIIUC, the optimisation is the same, but all it does is tell the compiler what the hot path is likely to be and so the code won't 'jmp' to it; the instructions are likely to be in I-cache.
- steerablesafe 6y ago
- djoldman 6y agoLet's say you churn something out in python and it works the way you like but you need it to complete faster. You move it to C/C++ (after not being able to speed up the python code using FFI or something else). Do you go C or C++? Even if I'm writing C++, I find myself using a restricted subset that is mostly C.
- Sebb767 6y agoBut why? C++ has some pretty good upgrades over C - like classes, smart pointers and a better type system. Even if you're not writing idiomatic C++20 code, having a better structure alone is worth it IMO. If you don't need classes, maybe you should look into Rust - it's quite a bit more restrictive, but it allows a nice, functional style with similar performance while avoiding most of the pitfalls and footguns of C.
- huhtenberg 6y agoSmart pointers aren't an upgrade over C per se. It's a coding pattern that has its specific use, but that's definitely not something that's missing from C or a natural extension to how things are generally done in it.
- bluGill 6y agoIf you are porting Python to something else, then smart pointers are a very useful upgrade that save you from a ton of analysis that Python just did for you. Garbage collection does almost the same thing, but you need to deal with python's "with" somehow then.
- saurik 6y agoThe #1 feature I currently want is the ability to do an implicit lambda capture of a structured binding, at least by reference. I appreciate there are interesting corner cases of like, bindings to bitfields: I simply don't need those corner cases solved... if it just supported a handful of the most obvious cases I would be so so so happy, and then they can spend the next decade arguing about how to solve it 99% (which I say as we know it won't be 100%... this is C++, where everything is some ridiculous epicycle over a previous failed feature :/). (edit:) OMG, I found this feature in the list!! (It was in the set of structured bindings changes instead of with the changes to lambda expressions, which I had immediately clanged through.) I need to figure out now what version of clang I need to use it (later edit: I don't think clang has it yet; but maybe soon?)... this is seriously going to change my life. https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.html#structbind-specs https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
- w0utert 6y ago>> this is seriously going to change my life. Now I'm curious. Can you give a small code example of the kind of thing this solves and how it will change your life? ;-)
- saurik 6y agoI constantly use both lambdas and structured bindings; without this feature, I am having to constantly redeclare every single not-a-variable I use in every lambda level and then maintain these lists every time I add (or remove, due to warnings I get) a usage. Here is one of my lambdas: nest_.Hatch([&, &commit = commit, &issued = issued, &nonce = nonce, &v = v, &r = r, &s = s, &amount = amount, &ratio = ratio, &start = start, &range = range, &funder = funder, &recipient = recipient, &reveal = reveal, &winner = winner]() noexcept { return [=]() noexcept -> task<void> { try { And like, at least there I am able to redeclare them in a "natural" way... I also tend to hide lambdas inside of macros to let me build new scope constructs, and if a structured binding happens to float across one of those boundaries I am just screwed and have to declare adapter references in the enclosing scope (which is the same number of name repetitions, but I can't reuse the original name and it uses more boilerplate).
- DubiousPusher 6y agoHaven't been keeping up. Is there a module solution yet. #include is cursed.
- SavantIdiot 6y agoWhy is it cursed? Package managers are the wrong way to go for C++, IMHO. Just look at the bugs and bloat that every package manager is suffering right now. Rust isn't far behind. Keep C++ away from this. EDIT: I just learned module systems are NOT package managers.
- icholy 6y agoA module system and a package manager are two separate things.
- DubiousPusher 6y ago1) Headers cause programmers to take dependencies without realizing. (Especially when unity builds are setup). 2) They are fragile because they involve putting file paths into the code. 3) They cause build information to be in the code rather than with the other build information. To find out what is really being consumed I have to search every code file. 4) They cause all kinds of issues for beginners such as multiply defined errors. 5) They cause the compiler to revisit code hundreds even thousands of times bloating build times. (This is such an extensive problem a small industry has sprang up to address it i.e. precompiled headers, unity builds, fastbuild, etc) 6) They introduce confusing bugs (someone modifies a header in a dependent library but not the dependency, literally had to fix this for a 10 year+ game programmer at a studio you would know. Turns out adding virtual functions in a header will cause an off by 1 vtable lookup and hilarity insues.) > Package managers are the wrong way to go for C++ I didn't say anything about a package manager. Modules don't require package managers. In .net you can use Nuget or not but the complier understands how to take source and an assembly and hook them up. I just want a sane way to tell the compiler to build one thing and then use that when it builds the next thing. Rather than this weird concept that every TU has to stand completely on its own.
- oblio 6y ago
- nightowl_games 6y agoIn the first example, there is nothing inside the lambdas, doesnt that mean that _nothing_ will be captured? ie: including `this`?
- OskarS 6y agoNot quite sure what example you're referring to, but you mean if you do a lambda like this? auto add = [](int x, int y) { return x + y; }; Then yes, nothing will be captured. This is a pure function lambda. It's essentially just a convenient way to create a function pointer, and will in fact implicitly convert to a C function pointer. This is very useful with C libraries that use function pointers as callbacks (they usually provide the "this" equivalent as an argument instead of a capture).
- tomcam 6y agoIncredible job! Thank you.
- SavantIdiot 6y agoThis one-page format using "concept" -> "example" -> "reasoning" is fantastic for people like me who used C++ a lot in the past, and haven't touched it* in decades but still want to keep up to date. It probably helps that the author understands this enough to ELI5. So Thanks Oleksandrikvl whoever you are. * And by "touched it" I mean used its deeper features, not just STL containers and simple classes (and for/auto). (I still use it for TFLiteMicro, but generally I see that most users are topical C++ programmers, like me.)
- gowld 6y ago> This one-page format using "concept" -> "example" -> "reasoning" is fantastic I agree, but I don't think that's happening here. It's documenting C++ "Concept" which is the technical name for a certain part of the C++ language. It's a great article though.
- arcticbull 6y agoIf C++ was an octopus made by stapling extra legs to a dog, it's now just a giant pile of legs, and nobody's heard a bark in decades.
- deleted 6y ago[deleted]
- sudopluto 6y agowhat a snarky and unproductive statement
- ttul 6y agoAlternatively, C++ is an extremely mature language that has evolved through a painstakingly well considered process involving some of the brightest minds in computer science across multiple decades. It continues to deliver on the promise of providing the structure you want, without any undue runtime cost.
- arcticbull 6y agoMy criticism stems more from C++'s steadfast refusal to drop backwards compatibility, in any way, for anyone, ever -- while also adding new features. What this means is that new features can't provide the guarantees they can in other environments leading to "ruined fresco" [1] syndrome. Concrete example: std::move. Move constructors can copy, and `std::move` doesn't move. Naturally, it just casts your T onto `std::remove_reference_t<T>&&`. Because why not. It also leaves your source object in an undefined but totally accessible state -- whose validity is up to the implementor's convention! I think std:: collections are totally useable after they've been moved (correct me if I'm wrong) but your own types may just explode or fail silently. Talk about a giant footgun. This approach leads to poor imitations of features from other languages getting stacked on top of the rickety footbridge that is K&R C. It's specifically the evolutionary design philosophy that I take issue with. The language has become borderline impossible to reason about. Quickly, what's the difference between a glvalue, prvalue, xvalue, lvalue, and an rvalue? And the compiler, in the name of backwards compatibility, sets out not to help you because adding a new warning might be a breaking change. I've got easily 15 years of experience with C++ - granted, not daily or anything. To figure out what's actually happening, you need to understand 30 years of caveats and edge cases. [1] https://www.npr.org/sections/thetwo-way/2012/09/20/161466361/woman-who-ruined-fresco-of-jesus-now-wants-to-be-paid https://www.npr.org/sections/thetwo-way/2012/09/20/161466361...
- fatbot77 6y agoI’d love to see reflection in the language.
- steveklabnik 6y agoYou should check out the "metaclasses proposal."
- sriram_sun 6y agoFTA: if constexpr(Addable<T>){ /.../ } else if constexpr(requires(T a, T b) { a + b; }){ /.../ } The compiler knows that Addable<T> is a concept at this point right? Is the constexpr required?
- gpderetta 6y agoAddable<T> should evaluate to bool, so you can actually use it with a plain if. But a plain if requires both true and false branches to type check and if your T is not actually addable and you use operator+ in the true branch you will get a compilation error.
- sriram_sun 6y agoAah got it. Thank you!
- nec4b 6y agoI have a suggestion for HN admins. There could be a thread about Rust superiority pinned to the top of HN where the Rust "brigade" could promote their chosen tool supremacy all day long and in return leave threads about other languages alone. Otherwise almost any thread about C, C++, C#, Go, Java, JavaScript,... is getting quickly derailed from Rust aficionados.
- oblio 6y ago> C, C++, C#, Go, Java, JavaScript 3 of those are not like the rest. Rust evangelists rarely go (or at least do it less) after C#, Java or even Javascript threads. 10 points if you guess why. The overaching commonality of Rust evangelism is to target C/C++. And they're probably right :-)
- nec4b 6y agoFind me a Go, D lang or Zig thread from this year untouched from Rust "evangelism".
- coder543 6y agoNot only did you change the list of languages under discussion just now, you also included Go, which oblio specifically did not say would avoid discussions of Rust. You’re moving the goalposts, and complaints about discussions of Rust tend to be far more annoying than the actual discussions. How dare people want to discuss related languages they enjoy? I mean, right? Most language discussions will have people join in and discuss other languages. I’ve spent quite a few words in this very thread discussing Go’s package manager! Should I apologize to someone? No... I think language discussions normally involve discussions of languages.
- oblio 6y agoGo is frequently attacked by Rust evangelists because they feel, and they seem right, that Go is a programming language evolutionary dead end. It's a very practical language, so very popular, but based on programming language theory from 40 years ago, with a very low adoption of concepts from the last 2-3 decades. The risk being that in 20 years we'll wake up to the Go fad and realize that many people had been writing mountains of already legacy code from day 1, 20 years before. And those mountains of legacy code will have to be maintained because nobody's going to throw away so much working code. Both D and Zig are direct competitors for Rust so I don't understand the fuss. This tango goes both ways, it's just that there are fewer D or Zig evangelists out there, overall. But they do visit Rust threads, too ;-) And that's not bad, cross pollination is good. Insularity is bad.
- rsp1984 6y agoI'm probably going to make a few enemies with this opinion, but I think modern C++ is just an utterly broken mess of a language. They should have just stopped extending it after C++11. When I look at C++14 and later I can't help but throw my hands up, laugh and think who, except for a small circle of language academics, actually believes that all this new template crap syntax actually helps developers? Personally I judge code quality by a) Functionality (does it work, is it safe?), b) Readability c) Conciseness d) Performance and e) Extendibility, in this order, and I don't see how these new features in reality help move any of these meaningfully in the right direction. I know the intentions are good, and the argument is that "it's intended for library developers" but how much of a percentage is that vs. just regular app/backend devs? In reality what's going to happen is that inside every organization a group of developers with good intentions, a lack of experience and too much time will learn it all and then feel the urge to now "put their new knowledge to improve the codebase", which generally just puts everyone else in pain and accomplishes exactly nothing. Meanwhile it's 2021 and C++ coders are still - Waiting for Cross-Platform standardized SIMD vector datatypes - Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU - Debugging cross-platform code using couts, cerrs and printfs - Forced to use boost for even quite elementary operations on std::strings. Yes, some of these things are hard to fix and require collaboration among real people and real companies. And yes, it's a lot easier to bury your head in the soft academic sand and come up with some new interesting toy feature. It's like the committee has given up. Started coding C++ when I was 14 -- 22 years ago.
- chrisseaton 6y ago> I'm probably going to make a few enemies with this opinion, but I think modern C++ is just an utterly broken mess of a language. They should have just stopped extending it after C++11. This is the popular refrain of the day, so I don't know why you cage this as if you're saying something controversial.
- whimsicalism 6y agoThis is a popular (and increasing) trend in HN comments.
- ChuckMcM 6y agoLanguage discussions are always somewhat like debating the merits of various sports teams. Because the underlying computer architecture is the same, the how of expressing intent to the compiler for what you want it to do is always a mix of functional capabilities and aesthetics. The C++ changes to templates are great, but they are only great if you like templates. Just like with enough cheese on them I'll eat brussels sprouts but I'm not a fan. Similarly with the other new features, that folks who love C++ are really excited about. If I were advising graduate students I might have them evaluate the text to code ratio of various programming environments. I think it would make for some interesting insights into the ability to express execution as language. Then if you added 'total time to implement' from idea, and errors per thousand lines of code in the various choices you might be able to derive some metrics for how "effective" these languages were. That said, I really appreciate someone putting down examples of all the changes. That is much easier for someone like me to internalize than the change text in the standard!
- the_duke 6y agoI was really looking forward to concepts. But the actual implementation seems like a syntactic and ( partially) semantic mess to me. Obscure syntax (`requires requires`), soooo many different ways to specify things, mangling together with `auto`, mixing of function signature and type property requirements (`&& sizeof(T) == 4`), etc etc. This reeks of design by committee without a coherent vision, and blows way past the complexity budget I would have expected to be spent. Rust (traits), Haskell (type classes) and even the Nim/D metaprogramming capabilities seem simple and elegant in comparison.
- gpderetta 6y agoThe original C++0x concept proposal had proper type signatures and was based, I think, on more traditional type theory. But it had to be continually tweaked as it did not work well in practice so it grew in complexity a lot. Additionally the only implementation was extremely slow to compile. It was taken out of the standard, and the new version (aka concept-lite) is actually much simpler, although expression based. We lost the ability to type check template definitions though. Far from being a design by committee, I think for the most part is the brainchild of a single author. The 'auto' thing is definitely a committee addition as many vetoed "implicit" templates and requiring auto after the concept name in the shorthand form was the compromise that pleased no one [1]. [1]: this is an obvious manifestation of Stroustrup's Rule
- AlexanderDhoore 6y agoIs there a /r/nottheonion but for programming? You can't make this stuff up. "In C++20 stateless lambdas are default constructible and assignable which allows to use a type of a lambda to construct/assign it later. With Lambdas in unevaluated contexts we can get a type of a lambda with decltype() and create a variable of that type later." "Sometimes generic lambdas are too generic. C++20 allows to use familiar template function syntax to introduce type names directly."
- petters 6y ago[](){}; was already valid C++ syntax. Is []<>(){}; now valid? Feels right to me! Edit: This is a pretty strong new standard overall. Concepts and modules are something C++ needs.
- veselin 6y agoAs somebody who uses c++ daily and spends a lot of time compiling, I am really excited about modules. Unfortunately, the latest even unreleased g++ v11 and clang v8 only say they support them partially. Does anybody have any experience trying them out? Do they work,l and are they ready for production use?
- account4mypc 6y agoi tried to evaluate whether they would help build times at all. this is the only reason i want them. based on some research, they don't if you have parallel builds (since a module must be built before its users/not in parallel). so i think this lessened excitement from users/compiler devs/build tool makers. and it was enough to convince me to just buy more cores to parallelize builds more rather than put in work for half baked modules
- veselin 6y agoThere are already precompiled headers. They are a big speedup as far as I know, but semantically problematic. Maybe if you use them, you will not see a speedup.
- webaholic 6y agoIf someone is looking to learn a new language should they spend the effort on learning C++ or Go/Rust/<others>?
- gpderetta 6y agoUnless you are doing it mostly for intellectual curiosity, don't just learn a language for the sake of it. Pick an area you are interested in an learn whatever language is the most used in that domain.
- elzbardico 6y agoSometimes I get the feeling that we are 2 standards revisions away from C++ compilers to pass the turing test.
- 72deluxe 6y agoI found the cppcon video on c++ 20 features to be very informative and I am honestly excited to use ranges and other items mentioned, unlike the other guys on here who hate progress. https://youtu.be/FRkJCvHWdwQ https://youtu.be/FRkJCvHWdwQ
- hwc 6y agoUm, dumb question here, but how do I use c++20 modules with makefiles in such a way that dependencies are handled correctly?
- iskander 6y agoAs an academic, it's really surprising to see people describe the C++ language cabal as academia. Like, no one is getting tenure for dumping more language features into that witch's brew.
- superkuh 6y agoNow try compiling code with any of those features on a distro older than 3 year. It's not gonna work. C++xx is future shock.
- omar_kha 6y agoimagine trying to remember all those features.
- kyawzazaw 6y agoAnyone who works at trading firms chime in what version are they using? I see 17 for some, a lot stuck at 11.
- ncmncm 6y agoMany, many banks are stuck at '03, deploying on RHEL 6. The only motivation for a bank ever to make a clean break is if they must, just to attract talent. This is difficult for providers of services to banks, who are stuck at the level of their most archaic customer.
- mypalmike 6y agoI haven't been following C++ for quite a while but when I did, I wanted modules. And now it looks like they're here and they've done it wrong. Or at least missed an opportunity to do it really right. They've done the equivalent of * imports in languages like Java and Python. And style guides in those languages universally recommend against doing that. Why? With named imports, if you see a symbol anywhere in the codebase, its declaration is somewhere within the file itself. If you see a call to foo(), it's going to be either a local function or a declared import. With C++ modules (as with C++ includes) it could come from any of the imports, so you have to look outside of the file to figure out where it came from. Sure, IDEs help paper this over somewhat. But it just seems sloppy for a post-1980s language feature to throw all imports into the global namespace.
- yuushi 6y agoThat's because modules and namespaces are the same thing in languages like Python, whereas they are separated in C++. The code in the imported module will go into whatever namespace it is in within that module, not the global namespace.
- mypalmike 6y agoI had forgotten about C++ namespaces. It's been quite a while. I'm not sure that this addresses my concern though. Do namespaces enable the import of specific symbols from a module?
- socialdemocrat 6y agoSome years ago I would have thought all this would be really cool. But who are they kidding? What sort of people will be able to keep this whole language in their head. C++ books were thick bricks already 20 years ago, and students struggled hard to learn it. Now the language is like 3x as complex. Students are going to need a separate bag just for their C++ material. Sure you can write in a subset of C++ that is easy to get. But when did that ever work? Who has worked in a company and seen people able to stick to a minimal C++ subset? No, people get tempted and they start using all the new stuff. Short term it is a real gain. But once you hire junior developer who has to read this code, they suddenly have 3x as many concepts to learn and understand. I predict a serious recruitment problem with C++ down the road. Old timers today will start using all the new features. When management start trying to add new team members they start realizing that it is really hard to get quality C++ developers. Anyway who tries Go, Rust, Swift, Nim, D or some other moder/semi modern language are going to ask themselves why on Earth they would want to torture themselves with C++.
- nine_k 6y agoThere are good alternatives to C++: Rust and D. There is a number of languages with not quite as high but decent performance and varying expression power: Java, OCaml, Go, even Fortran for numerical stuff (not a joke; modern Fortran is quite advanced, and most likely runs faster then C++). I see rather few reasons to start a new project in C++ in 2021, even though in some niches nothing else is viable, sadly.
- ncmncm 6y agoIt is easy to know why the world's highest-paid programmers, coding for the world's most demanding applications, use C++ and nothing but C++: nothing else is even trying to be useful in those applications. C++ has sharp edges and pitfalls to stay clear of, so users ... do stay clear of them. A usable, better language would gain users. But nothing is even on the horizon. Rust is closest, but its designers have consciously chosen not to support the most powerful of C++ features, to try to keep the language more approachable. Yet, Rust complexity is already beginning to rival C++. Some of that complexity is in how to work around the language's deliberate limitations. As Rust matures it will suffer from unfortunate early choices in precisely the way C++ has, and will only get more complex. Every choice in the C++ design has been to provide better ability to capture semantics in libraries, so that independent libraries integrate cleanly with each other and the core language. People can use libraries with confidence that they are giving up no performance vs. open-coding the same feature. Access to the most powerful libraries depends on language features no other language implements. Thus, the best libraries will only ever be callable from C++ programs. With (literally!) billions of lines of code in production use, abandoning interoperability is not a choice to take lightly. When you start a big project, you never know what it may come to need. If your language "won't go there", your program won't, either, and you will be stuck with unpleasant choices. This is the concept of a language's "dynamic range", a more meaningful measure than "high" or "low" alone: how high can it reach, how low can it reach, how far can it reach, at once? C++ is king of dynamic range. Nothing else comes close, or is really even trying.
- posharma 6y ago“There are only two kinds of languages: the ones people complain about and the ones nobody uses.”
- Snelius 6y agoGreat job! Thank you!
- watersb 6y agoSafe C++ is indistinguishable from magic.
- uhhhhhhhhhhhhhh 6y agoC++ feels as great as typescript it just doesn't have a slick 'npm install'
- fbergen 6y agoIMO using things like [likely] has more potential to shoot oneself in the foot than improve performance. Using real execution statistic to determine branch prediction (at compile time) should be the new standard