All C++20 core language features with examples
oleksandrkvl.github.io
oleksandrkvl.github.io
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.
which language has standardized SIMD vector datatypes ? most languages don't even have any ability to express SIMD while in C++ I can just use Vc (https://github.com/VcDevel/Vc), nsimd (https://github.com/agenium-scale/nsimd) or one of the other ton of alternatives, and have stuff that JustWorksTM on more architectures than most languages even support
- Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU
what are the other native languages with a standardized memory model for atomics ? and, what's the problem with using libraries ? it's not like you're going to use C# or Java's built-in threadpools if you are doing any serious work, no ? Do they even have something as easy to use as https://github.com/taskflow/taskflow ?
- Debugging cross-platform code using couts, cerrs and printfs
because people never use console.log in JS or System.println in C# maybe ?
- Forced to use boost for even quite elementary operations on std::strings.
can you point to non-trivial java projects that do not use Apache Commons ? Also, the boost string algorithms are header-only so you will end up with exactly the same binaries that if it was in some std::string_algorithms namespace:
A) Boosts supports an enormous amount of compilers & platforms. To implement this support is an enormous amount of expensive preprocessor stuff that slows down the build & makes it hard to debug. B) Boost is inordinately template heavy (often even worse than the STL). This is paid for at compile time. Some times at runtime and/or binary size if the library maintainers don't do a good job structuring their templates so that the inlined template API calls a non-templated implementation. The first C++ talk I remember talking about this problem was about 5-7 years ago & I doubt boost has been cleaned up in its wake across the board. C) Library quality is highly variable. It's all under the boost umbrella but boost networking is different from boost filesystem, different from boost string algorithms, different from boost preprocessor, boost spirit, etc. Each library has its own unique cost impact on build, run, & code size that's hard to evaluate a priori.
Boost is like the STL on steroids but that has its own pitfalls that shouldn't be papered over. Maybe things will get better with modules. That's certainly the hope anyway.
Java is getting it soonish. https://openjdk.java.net/jeps/338
Rust has it (but it's fairly platform specific) https://doc.rust-lang.org/edition-guide/rust-2018/simd-for-f...
Dart has it https://www.dartcn.com/articles/server/simd
Javascript has it https://01.org/node/1495
It's actually a bit impressive how many languages have it at this point.
> what are the other native languages with a standardized memory model for atomics
Rust, C, Go?
> It's not like you're going to use C# or Java's built-in threadpools if you are doing any serious work, no ?
Define "serious". By most metrics JVM apps run at 1->2x the speed of C++, that's really not terribly slow for a managed language. On top of that, there are a lot of places java can outperform C++ (high heap memory allocation rates). Java's threadpools and concurrency model is, IMO, superior to C++'s.
> Do they even have something as easy to use as taskflow
Several internal and external libs do. Java's completable futures, kotlin's/C#'s (and several other languages) async/await. I really don't see anything special about taskflow.
> can you point to non-trivial java projects that do not use Apache Commons
Yes? It's a fairly dated lib at this point as the JDK has pulled in a lot of the functionality there and from guava. We've got a lot of internal apps that don't have Apache commons as a dependency. I think you are behind the times in where Java as an ecosystem is now.
- Java: incubation stage (how is that different from https://github.com/VcDevel/std-simd). Also Java is only getting it soonish for... amd64 and aarch64 ??
- Rust: those seem to be just the normal intrinsics which are available in every C++ compiler ?
- Dart: seems to not go beyond SSE2 atm ? But it looks like the most "officially supported" of the bunch
- Javascript: seems to be some intel-specific stuff which isn't available here on any of my JS environments ?
* Standardized memory model
- Literally false for Rust : https://doc.rust-lang.org/reference/memory-model.html
- The C11 one directly comes from C++: https://stackoverflow.com/a/8877562/1495627
- The Go one does not seem to support acquire-release semantics, which makes it quite removed from e.g. ARM and NVidia hardware from what I can read here ? https://golang.org/pkg/sync/atomic/
D does:
#if defined(__NEON__)
"portable" SIMD goes here
#elif defined(__ALTIVEC__)
different "portable" SIMD goes here
...With a compiler error, the user unambiguously knows if the SIMD hardware is being used or not.
C# https://docs.microsoft.com/en-us/dotnet/standard/simd and https://devblogs.microsoft.com/dotnet/hardware-intrinsics-in...
Spot the difference:
C++: Conan (barely adopted), vcpkg (barely adopted), single header file libraries (!!!)
Java: Maven (de facto standard), Gradle (compatible with Maven), Ivy (compatible with Maven), heck Ant (compatible with Maven).
C#: Nuget.
I began C++ coding over 20 years ago as well, and it required reading thick books even then. I remember my class mates at Uni really hated software development all because of C++. It was way too hard as a beginners language, even 20 years ago.
I look at all these new features, and I am like: How on earth are you going to teach all this crap to students?
They have painted themselves into a corner. It becomes a language only for those who have already programmed it for 10-20 years.
This idea, that it is only for library developers is a bunch of crap. A lot of learning a language is really about reading the code for the standard library. That was one of the beauties of writing Go code. You regularly look at standard library code and is even encouraged to do so. It teaches you a lot about good style.
Same deal with I program in Julia. Looking at library code is totally normal and common.
Except in C++. I avoided looking at library code like the plague. And I suppose, now it will only get worse.
The worst part of this is that this isn't just a problem for C++ developers but also for everybody else. So many key pieces of software relies on C++ code. It becomes ever harder to migrate that code or interface with that code as C++ complexity grows.
That was the beauty of a language like Objective-C. Unlike C++ it is a fairly simple language which you can interface easily with. The result was that porting to Swift was really easy. When porting iOS apps to Swift I could pick individual functions and rewrite them to Swift.
There is no hope doing anything like that with C++.
You don't. You teach "A tour of C++ 2nd edition"[0] which presents a clean and smaller subset of the language people can wrap their mind around, with everything someone new to modern C++ needs to know to be effective. And you supplement this with "C++ Core Guidelines"[1] which can be enforced by code analysis and provide some examples of common mistakes or questions people might have.
You do not need to know all the details of the language and know every single features. And wouldn't teach everything to a student.
But it's true that there is some overhead due to the complexity of the language.
[0]: https://www.stroustrup.com/tour2.html
[1]: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
This is the popular refrain of the day, so I don't know why you cage this as if you're saying something controversial.
There are currently enclaves of developers who know varying versions of C++. There's a good chance that a 20-year C++ veteran would have to consult the documentation for syntax. That's concerning. Defining what something isn't is nearly always more important than defining what it is, and C++ is seemingly trying to be everything.
This is a common saying because it is a common occurrence.
People who use the language effectively know all about the complaints. Those people live with their complaints knowing no other language even comes close to meeting their needs. No language on the horizon is even trying to meet their needs.
C++ usage is still growing by leaps and bounds. Attendance at ISO Standard meetings is soaring; until Covid19 killed f2f meetings, each had more than any meeting before; similarly, at conventions. Even the number of C++ conventions held grows every year, with new national ones arising all the time.
Rust is having a go at part of the problem space, and making some headway. But more people pick up C++ for the first time in any given week than the total who have ever tried Rust. It is still way too early to tell whether that will ever not be true.
So the HN trend is very much an echo-chamber phenomenon, with no analog in the wider world.
> This is a common saying because it is a common occurrence.
Ha ha. This is not applicable for software, and I assume, for some craftsman.
What's the percentage of software developers that actually get to choose their tools? 40%? 60% at best? Though most likely it's just 20%.
Most projects are pre-existing, it's only natural. You can't create more projects than those already in existence, once a field matures a bit. Which means that you have to use what's already there.
Plenty of people are forced to use bad tools. And they can for sure blame them.
These places also have all the resources as well.
I'm sorry but can we stop hating on "academics"? No one in research matches your description. The intersection of academia and C++ contains only practitioners (like in the industry), who just want their code to work; and maybe some verification people who'd rather wish C++ was smaller because it is a hell of a beast to do static analysis on. Both these categories are real people having real use cases. The programming language crowd is generally more interested in stuff like dependent types or effect systems, not templates.
> soft academic sand
shrug.
(I have been coding in C++ on and off professionally since 1985 and I do like some of the C++11 and c++14 features. The pointer improvements are great but the template stuff is a complete joke on us).
Actually, the rationale behind the language features you're criticizing is that people in the real world were already using some techniques in C++ in a needlessly complex and convoluted way, and these new additions not only simplify these implementations but also allow the compilers to output helpful, user-friendlier messages.
Take concepts, for example. You may not like template metaprogramming, but like it or not they are used extensively in the real-world, in the very least in the form of STL and Eigen. Template metaprogramming is a central feature of C++ consumed by practically each and every single C++ developer, in spite of rarely producing code them. Does it make any sense at all to criticize work to improve a key feature that benefits each and every C++ programmer, in spite of not having to write code with it?
And no one of sane mind would argue in favour of shoehorning #include and #ifndef/#define in detriment to a proper module system.
Just because you aren't familiar or well-versed with some C++ features, or aware of how extensively they are used, it doesn't mean they are not used or that the stuff you don't know automatically qualifies as a trainwreck.
Why C++14? The changes were very minor and mostly about being able to declare lambda functions with auto, which is extremely useful.
> Waiting for Cross-Platform standardized SIMD vector datatypes
I only know of ISPC having this, but there are also lots of SIMD libraries for C++ that are small and have minimal dependencies.
> Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU
std::thread, atomics, and mutexes were added in C++11 and work extremely well. OpenMP is in the top four compilers if someone wants super easy fork-join parallelism. What other languages make C++ look archaic here?
> Debugging cross-platform code using couts, cerrs and printfs
Both visual studio and Qt Creator have made this unnecessary for a long time (if you can do step through debugging). What other language are you thinking of that makes C++ look archaic here?
> Forced to use boost for even quite elementary operations on std::strings.
That's completely ridiculous. It is easy to avoid boost these days (thank god). This is DEFINITELY not worth using boost for. First you can use https://github.com/imageworks/pystring on top of what C++ already has combined with regular expressions.
I don't think anything you listed is actually a problem. If you had talked about not having a standard networking library or standard serialization it might have made more sense.
> a) Functionality (does it work, is it safe?), b) Readability c) Conciseness d) Performance and e) Extendibility
I use a lot of library features after C++11. Variant, span, and string_view are the most important ones. As to language features, structured bindings and variable templates come to mind. They pretty much hit all of your code quality points. I don't think these are for "a small circle of language academics" either (I'm definitely not in that "small circle"). Syntax-wise, meta programming can get ugly yes. Even Stroustrup himself doesn't like it. I guess at this point it's just for "historical reasons".
> Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU
I think this one comes down to that there are a vast range of parallel computing models out there, and C++ wants to have generality. I used to write a lot of MPI programs targeting the super computers. I don’t think any language would want to include that in the standard…
> Debugging cross-platform code using couts, cerrs and printfs
What’s wrong with printing? I even debug JavaScript programs with console.log(). It’s convenient.
If you just do local dev, debuggers work pretty well, you can debug however you want. I was unfortunate enough to have pretty much always worked on platforms that is hard to have a good remote debugging session, due to hardware capacity, legacy toolchain, or even ssh-ing onto the host being hard enough due to security. But that's hardly C++'s fault.
> Forced to use boost for even quite elementary operations on std::strings
It’d be great if std::string has more features. But I don’t think it a big deal. Personally I don’t like linking boost to my programs, so I just write my own libraries for that. It’s just elementary operations anyway.
> Waiting for Cross-Platform standardized SIMD vector datatypes
We sort of have this? compiler loop vectorization is, effectively, this. Granted it's not standardized.
> nonstandard extensions ... to run computations in parallel on many cores
std::thread?
> Debugging cross-platform code using couts, cerrs and printfs
True, but i think this is not the language's fault. C/C++ debugging tools are great (the best?).
Debugging any sort of meta-programming is a mess; would definitely agree w/ that. hopefully concepts will help.
> Forced to use boost for even quite elementary operations on std::strings.
This one i agree with.
> > Waiting for Cross-Platform standardized SIMD vector datatypes
> We sort of have this? compiler loop vectorization is, effectively, this. Granted it's not standardized.
Auto-vectorization isn't remotely capable of what an engineer is capable of doing through intrinsics.
> > nonstandard extensions ... to run computations in parallel on many cores
> std::thread?
Compare that to the capabilities provided by Thread Building Blocks.
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n355...
They probably meant something more declarative, along the lines of OpenMP.
Most STL algorithms can be executed in parallel from C++17.
It is standardized and widely implemented, just not part of the C++ standard itself.
I’m not waiting for anything, I’m writing non-cross platform ones for years now http://const.me/articles/simd/simd.pdf http://const.me/articles/simd/NEON.pdf
These things are specific to CPU architectures, but other then that they’re cross-platform and de-facto standards set by Intel and ARM. Same source code builds with all mainstream compilers, regardless on the target OS.
> nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores
OpenMP is not part of C++ standard, but it’s still a standard in the sense they have a complete specification: https://www.openmp.org/specifications/ Mainstream compilers are reasonably good at implementing these specs.
> Debugging cross-platform code using couts, cerrs and printfs
Debugging story is not great outside MSVC, but it’s not terrible either. When I needed that, gdb worked OK for me.
> Forced to use boost for even quite elementary operations on std::strings
I agree the ergonomics can be better, but I’m not using boost, and I see improvements, e.g. std::string_view in C++/17 helped.
If you actually care about performance, and presumably anyone that wants to use SIMD vector types does, you need to fit the higher-level data structures to the nuances of the microarchitecture you are targeting. Compilers don't do optimization at that level, you have to write the code yourself. Thin wrappers on compiler intrinsics is actually the right level of abstraction if you want to exploit those capabilities.
Similarly, how code is parallelized is completely dependent on what you are trying to do, the software architecture, and the silicon microarchitecture; there is no way to usefully standardize it outside of use cases so narrow they probably don't belong in C++. Parallelization in practice happens at a higher level of abstraction than the programming language.
And FWIW, I use many of these new C++ language features in real software every day because they provide immediate and compelling value. I am not an academic.
Binary interface complexity is actually a huge reason why people rewrite stuff in C. When you write in C, you get symbols and simple calling conventions. Makes it easy to interoperate.
It does, but it also has the ability of generating inefficient code. Sure, it's often the developers fault but I feel like it's much easier to shoot yourself in the foot in terms of performance in C++ compared to other compiled languages.
Some real-life examples for me:
* Missing a '&' for a function parameter resulting in that object being copied for each function invocation
* Adding a couple extra chars to an error message string in an inlined function which caused that function to then be 'too large' to inline according to the compiler
> 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?
I do. There are a lot of features introduced since C++11 that make my life much easier. Sure, it's always scary to have to learn new things, but once you get over that hump, you start to see the benefits. Concepts and constexpr cut down on the template boilerplate crap a lot. Being able to use the auto keyword in more contexts means less repetition. Modules get rid of the ugly hack that is the preprocessor. std::span means I don't constantly have to pass around a pointer and length, or create a dedicated struct to encapsulate pointer+length. Sure, there are some more obscure features whose usefulness are questionable, but for a design-by-committee language, they're doing a slow but sure job of moving past the language's old warts.
> 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.
Feature adoption doesn't happen overnight. Remember, we're talking about a decades-old language burdened by backwards compatibility - it took a long time for people to migrate from supporting C++03 to dropping it in favor of C++11. Give it five or ten years, and I reckon you'll see people make use of C++17 and C++20 in much greater numbers.
> Waiting for Cross-Platform standardized SIMD vector datatypes
No argument there. That said, all mainstream compilers already have "immintrin.h" for x64 and "arm_neon.h" for ARM, and using them isn't particularly difficult.
> Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU
Are you aware that std::thread has existed since C++11, and std::jthread and coroutines are in C++20?
> Debugging cross-platform code using couts, cerrs and printfs
This is a programmer problem, not a language problem. gdb exists, lldb exists, the Visual Studio debugger exists, and they're not particularly hard to pick up and use - if you're still using print statements to figure out why your application is crashing, that's on you.
> Forced to use boost for even quite elementary operations on std::strings
std::string is an RAII-managed bag of bytes. What kind of operations are you looking for? Stuff like concatenation and replacement can already be done in C++11 with std::string and std::regex. If you want to do lexical operations, like case conversion or glyph counting, then an encoding-aware library is a better solution.
> Give it five or ten years, and I reckon you'll see people make use of C++17 and C++20 in much greater numbers.
Frankly, the thought of it makes me want to migrate to Rust.
> Are you aware that std::thread has existed since C++11, and std::jthread and coroutines are in C++20?
Sure, but very low level. I'd be great to have a standard for something like TBB or OpenMP.
> std::string is an RAII-managed bag of bytes. What kind of operations are you looking for?
Looking enviously at Javascript strings and boost string algorithms...
The answer here is modules. Improve the story on shipping C++ libraries, and then who cares if it's in the "standard library" or not? It's not like anyone in JS land for example cares if something is native to the language or in a library since adding a library is trivial & easy.
Tbb is great.
I don't understand... How do these features not address those points?
> a) Functionality (does it work, is it safe?)
constinit, consteval and all the remaining constexpr improvements are a massive step for ensuring the "compile-time-ness" of code:
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
There's several more sharp edges being removed too. It's of course not going to tackle the fundamental safety concerns the way Rust is doing, but that would be a new language (like Rust is) anyway.
> b) Readability
requires is infinitely more readable than the SFINAE we had to write so far:
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
Besides that elephant in the room, most of these changes involve making the code either simpler to read/write (too many to name) or more explicit (consteval/constinit, attributes, ).
> c) Conciseness
Half the features contribute to this in one way or another (e.g. see previous point, or the spaceship operator), but there's also a whole list of syntactic sugar being added:
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
> d) Performance
What about coroutines?
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
> e) Extendibility
Various fixes to customization points:
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
For the uniformed such as myself, what happened beginning at C++14? What exactly was the fundamental shift?
The language has gotten continuously more powerful since 2011, albeit in smaller increments until C++20 when several big features landed.
Good C++11 looks practically nothing like C++98, and good C++20 looks as little like C++11.
It is really getting more fun all the time, as old crud falls away, and you can just say more and more just what you mean. Improved type-inference capabilities are doing a great deal of the heavy lifting.
> - Using nonstandard extensions, libraries or home-baked solutions to run computations in parallel on many cores or on different processors than the CPU
SIMD computation and multithreaded parallel computations were largely solved with execution policies. C++17 added multithreaded and multithreaded+SIMD execution policies, C++20 added single threaded SIMD execution policy.
I would argue that standardizing SIMD vector extension datatypes is an anti-feature for all cross platform programming languages. Writing AVX512 code is very different from writing NEON code. If the compiler autovectorizer doesn't generate good enough code for you, you have no choice but to use the non-cross platform vendor specific intrinsics anyway. If a SIMD datatype and the operations you could perform on it were standardized, it would necessarily have to be a very low common denominator. I don't even know what the lowest common denominator between MMX, SSE2, AVX2, AVX512, NEON and Altivec (to name a few) even is.
Note that the autovectorizers in GCC and Clang (not MSVC) are very, very good. If you structure your data in the way it would have to be structured if one were going to write hand-vectorized code anyway, GCC and Clang will, with a high probability, vectorize it correctly.
I don't know what a standardized language feature for execution on different processors than the CPU would even look like. What languages have this, and what does it even look like? Can you give a code sample?
> - Debugging cross-platform code using couts, cerrs and printfs
I don't think I understand what you're suggesting. On second thought I definitely don't understand what you're suggesting.
Are you suggesting that the C++ standards committee should standardize a _debugger_? You'd have to standardize the ABI first. There's no way to do that; 32 bit x86 with its 8 registers must necessarily have different calling conventions than ARM with its 32 (I think? it's been a while) registers.
If you're suggesting that the committee standardizes a UI, there's no way you're going to get the Visual Studio team and the GDB team to agree on what a debugger ought to look like. I don't even know where a mediator would even begin to start suggesting anything.
If you're suggesting that current debugger offerings such as the Visual Studio debugger and GDB aren't good enough, I dunno what to tell you. They work for me.
> - Forced to use boost for even quite elementary operations on std::strings.
Can you give an example? The big thing I used boost string stuff for was boost::format, but now that there's std::format I don't need that anymore.
(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.ht...
However a full destructuring bind, à la Lisp, hasn't. You can't do `for (auto& [a, [b, c]] : some_container_of_structs)` which is handy for taking apart all sorts of things.
Relatedly there's no "ignore" though it exists in function declaration syntax: you can write `void foo (char the_char, int, long a_long);`. But you can't ignore the parts of a destructure you don't need: `auto& [a, , c]`. This capability is sometimes useful in the function declaration case but is quite handy, say, when a function returns multiple values but you only need one (consider error code and explanation).
And variadic destructuring...well I could go on.
I haven't attended a C++ committee meeting in 25 years (and didn't do a lot when I did) so I have no reason to complain.
Lisp destructuring comes directly from macros: CL's destructuring lambda lists and macro lambda lists are closely related cousins.
Macros usually care about all their arguments. Reason being, they are designed to cater to those arguments; an unnecessary element in the syntax of a macro will just be left out from its design, rather than incorporated as a piece of structure that gets ignored. (The exceptions to it are reasonably rare that it's acceptable to just capture a variable here and there and ignore it.)
For example lambdas were added in C++11, but generic lambdas were cut out and only added in C++14.
"If you don't see anything between the commas, then fill it in with a compiler-generated symbol."
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? ;-)
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).
It's kind of weird structured bindings where not captured with [=](){} before, actually. I'm still stuck at C++11 for most of my work so I cannot use structured bindings at all, but I would not have expected to have to write that kind of monstrosity in C++17
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.
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/tensorf...
Basically it has plugins to discover/build various package types (autotools, cmake, bazel, setuptools, cargo), and the "interface" between packages is just the output of whatever the standard install target is for a given package. This makes it totally transparent whether your dependency is built-from-source in your workspace, coming from /usr/local via a sudo-make-install workflow, or coming from /usr via a system package.
Under this model, you never pull a dependency as a "subproject" with invocations like include or add_subdirectory; it's always using a standard find_package invocation, where basically the only requirement on participating packages is that they cooperate with long-existing standards like CMAKE_PREFIX_PATH and CMAKE_INSTALL_PREFIX. Vendoring a library is then not making a copy of it in your project tree, but rather as sibling project within the shared workspace that colcon builds.
Some public data that could be used as proxy for traction:
- Some companies using Conan in production can be seen in the committee for Conan 2.0 called the tribe: https://conan.io/tribe.html. That includes companies like Nasa, Bose, TomTom, Apple, Bosch, Continental, Ansys...
- The public repo for ConanCenter packages, got aprox +3500 pull requests in last year https://github.com/conan-io/conan-center-index/pulls. This doesn't count for contribution to the tool itself.
- https://isocpp.org/files/papers/CppDevSurvey-2020-04-summary... shows a 15% of adoption
- With +1600 subscribers the #conan channel in the CppLang slack is consistently ranked in the most active channels every month: https://cpplang.slack.com/stats#channels
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".
> bury your head in the sand if you want
Great chat, as always. :)
I don't understand this - they are not competing brands or sports teams but tools.
Why would it matter and to whom if C++ use would decline?
If use of C++ declines then I don't understand how that would make the language a lesser tool.
Choose the best tool for the job and all that.
Competition exists all around us, all the time, whether we like it or not.
And the competition between C++ and Rust is very clear. I, for example, would likely be spending more time / effort on learning the latest C++ standards if Rust didn't exist. And likely hate my life a little bit, unless I could exclusively stick to C++ "the good parts" if such a subset exists and I didn't need to interface as much with existing C++ code.
If C++ use declines, then there are fewer opportunities for me. So you can count me as a member of team C++.
The hypothesis is that C++ will decline because it becomes the lesser tool (where "lesser tool" means it excels only in increasingly small niches) if it doesn't adapt. That said, the C++ community seems to want to adapt and remain relevant, as indicated by its significant progress over the last decade.
As for why someone might care about the usage of a programming language: because "ease of finding developers" and "quality and breadth of ecosystem" are major factors in deciding on new projects. I.e., "the best tool for the job" is often the one with the broader ecosystem and more developers, all else equal. So these factors feed back on each other.
If the use declines to zero, then all the effort someone put into developing C++ compilers and related tooling had been for naught, as are C++ development skills.
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
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
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.
C++ does not have an equivalent, it's completely decentralized which results in more messy situation. As a result you have an open market where different people try to build different tools and approaches for their own problems, then try to get others to use them (similar to what Go had before go modules, we had lot of package managers to chose from at the time).
Instead of a top down decision it's a negotiation between the various actors. But the last thing we need is for the C++ standards committee to standardize a package manager. That would take forever to do, would result in a messy tool that tries to compromise with all the actors in some ways, make it very hard and slow to evolve over time and would likely result in a lot of pain, etc.
That is the role of the ISO C++ committee, is it not? They are the major stakeholders. They would just have to care enough. They cared enough to release C++20, didn't they? It's not like they never get anything done, which seems to be the implication a lot of people make in this discussion.
> Instead of a top down decision it's a negotiation between the various actors.
My understanding is that the various committee members represent the disparate interests of the broader C++ community. I agree it would be very much like a negotiation.
That doesn't mean that it can't be done. This whole thread is discussing things that have been done by the C++ committee: C++20.
> But the last thing we need is for the C++ standards committee to standardize a package manager. That would take forever to do, would result in a messy tool that tries to compromise with all the actors in some ways, make it very hard and slow to evolve over time and would likely result in a lot of pain, etc.
You just summarized my feelings about C++ in general. I would much rather people use Rust or Go or any number of other languages instead of C++, depending on project needs. Such opinions are rarely taken well in threads like this, though, so...
I've been trying to be optimistic and point out that C++ could get package management. If the C++ committee process works well, then the package manager should also end up turning out well.
I'll leave the reader to decide how well they think the long term direction and guidance of the C++ standard has been going and apply that to their feelings of a hypothetical future package manager.
Some people do occasionally use Bazel or other build systems on top of the Go build system for complicated monorepos.
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.
No. I'm not talking about either of those. Your whole comment is, unfortunately, irrelevant.
pkg.go.dev is not a package repo. It's just a place for documentation to be rendered. It renders documentation from third party hosted code, such as on GitHub or elsewhere.
"go get" predates Go Modules, which is the current package management system. The whole original design of "go get" was to simply download code from somewhere on the internet, and place it in the right spot of the $GOPATH. This has nothing to do with a proper versioned package manager like Go Modules.
AFAIK, "go get" was also never really designed for Google's internal use cases. They use a monorepo that was perfectly content with $GOPATH, and all their code was developed in the monorepo to begin with. There was nothing for them to "go get", except for the rare outside dependency that they were embedding into their monorepo, I would imagine. I've never worked for Google, these are just things I hear about.
Go Modules was also not designed for Google. It was designed for the community, based on findings from community developed package managers for Go. Google has no real use for it — again, they use a monorepo.
Nowadays, "go get" can be used with Go modules, but in practice, it feels like it almost never is. Maybe someone would use that command to upgrade an existing dependency, instead of editing the `go.mod` file to change the version there?
So, your comment just shows that you haven't researched this enough. Yes, Go Modules was still guided by Googlers, who were even more in control of the language direction back then than they are now. Yes, change always causes some drama. But, I'm not really here to explain the history of Go package management...
I'm just saying that C++ could have a nice, distributed package management system, it would just require the major stakeholders to all care and work together on it. The ISO C++ language committee is a finite number of people. They are the major stakeholders, as far as the language direction is concerned.
If they didn't have the power to enact major language changes, we wouldn't be here talking about C++20.
The stakeholders for Go were able to develop a package manager that is distributed (an idea compatible with how all C++ code is scattered across the web these days), and that achieved broad adoption, and this was some years after the language went into wide use.
It’s an extremely relevant analogue for C++ to study, if the committee members wanted a package manager badly enough.
> 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.
You edited this in while I was replying, but I agree entirely. Getting the committee to agree to a package management solution would be much more difficult than having a single behemoth guide the decision. Does that mean it is impossible and therefore no one could do it? Everyone here talks like it is impossible, but it doesn't really seem to be.
Currently, it seems almost nobody is taking that into account when packaging their wares for consumption by CMake, or distribution by Conan. Or if they do give it some thought, it always ends up making dubious assumptions, like "Clang == Linux", or "MSVC == Windows".
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.
It'll take some decades for the ideas to percolate, but language-specific package managers are definitely not the future.
Also, i'm terrified of this idea of "library-manager download code from internet and run on this machine", without all the tests and QA of individual dependencies like we have in Linux packages.
Also, i've seen so many times people adding dependencies to projects because they did not know the standard library already had what they needed. I get it, it is easier to "pip install foo" than to look for "foo" in the docs. I don't think any sane person can learn everything that is available in the standard library, but searching the docs is always insightful.
Even within Linux and BSD there are many flavours of package managers with slightly different naming schemes for their packages.
This fragmentation makes it impossible to have dependencies that just work. You need to either make users install things manually or every author has to probe multiple package names/locations using multiple tools.
Language-specific managers support all of the OSes and just work, especially for users of macOS and Windows (telling people their OS sucks may state a true fact, but doesn't solve portability problems)
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.
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.
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.
In the case of a GUI, I’d expect a modern Rust GUI toolkit binding to look like any other GUI toolkit binding: an FFI-like abstraction that parses its own declarative view format, and exposes handles from those parsed views for native controller methods to bind to. Y’know, QML, NIBs, XAML, those things. This kind of GUI toolkit doesn’t exactly have high requirements of the language it’s bound to. (And I don’t believe many people want the other, procedurally-driven kind of GUI toolkit in the year 2021.)
Re: distributed computing — I can see the argument for Rust being the antithesis of easy network “rolling upgrade” (e.g. via being able to recognize known subsets of unknown messages, ala Erlang); but pretty much all languages that support distribution are very nearly as bad in that respect. (Only the languages that have distribution that nobody else actually uses — e.g. Ruby, Python, etc. — are on Erlang’s side of the spectrum in this regard.) But in terms of pre-planned typed-message version migrations, Rust can do this more idiomatically and smoothly than many other languages, e.g. Go, Haskell, etc.
Re: web development — there’s actually a lot of activity in building web frontend SPAs using Rust compiled to WASM. Started with games, but has expanded from there. Not sure about web backends, but the argument is similar to distribution: you need to do it differently in a static compiled language, but of static compiled languages, Rust is really a pretty good option.
I won't take a GUI framework without a graphical designer, or a component ecosystem from companies selling GUI widgets in 21st century.
Distributed computing, again when thinking about distributed calls a la Akka, Orleans, SQL distributed transactions, I rather have the productivity of a GC.
Web development with Rust is nowhere close to the stack provided by JEE, Spring, ASP.NET, Adobe Experience Manager, Sitecore, LifeRay, Umbraco, enterprise RDMS connectors, ...
Rust best place is for kernels, drivers and absolute no GC deployment scenarios.
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.
People are trying out Rust in all of these spaces. I don't see why Rust is fundamentally unsuitable to these domains.
Now imagine how to implement such designer in a way that supports component libraries, without having the burden of using Rc<RefCell<>> everywhere, while allowing the user to rearrange the component widgets in any random ordering.
No such thing.
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).
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).
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.
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.
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.
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.
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.
From https://www.ffmpeg.org/about.html
"FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created."
After that:
"It contains libavcodec, libavutil, libavformat, libavfilter, libavdevice, libswscale and libswresample which can be used by applications. As well as ffmpeg, ffplay and ffprobe which can be used by end users for transcoding and playing"
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.
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/specific....
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.
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.
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++.
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.
There's no proof of this. The world's highest-paid programmers tend to work for FAANGs and a few other categories of businesses, and they might or might not work in C++, and they tend to move up the ranks by being able to scale humans (other devs), not raw tech.
It's a myth that being an über-geek is well paying, by the way.
But there is no necessary relationship between "the world's highest-paid", and your notion of "well paying". You could be simply wrong, or your measure of "well paying" could exceed what the actual "highest-paid programmers" cited get.
Dan Luu did a good essay about programmer compensation a few years back.
Could you show some examples of how you need to work around these deliberate limitations?
There is a corresponding list of features C++ doesn't have yet, and others it is precluded from having. That programmed move-constructors can fail sucks. Thst moved-from object's still exist sucks.
Providing examples here would be more work than I am prepared for just now. (I am not happy to say so.(
* Standard library user-provided allocators: in nightly, on their way to stable
* Move constructors: not in for technical reasons and performance reasons, not for approachability
* Inheritance: not in for technical reasons combined with a lack of demonstrated need rather than just desire, not for approachability
* Certain kinds of specialization: you're hedging with "certain", but specialization is in nightly, and used in the standard library.
* SFINAE: Rust doesn't use templates, so this as a direct feature doesn't make sense. I'm not aware of any proposal to include something similar in Rust, the team has never said that this wouldn't be in for approachability
> Somebody who knows Rust better, and C++, will be able to supply a longer list.
I don't think your thesis is accurate, so I don't think so. And if this is so obvious, as you claim, then you should be able to provide examples!
I see rather few reasons to start a new project in C++ in 2021, even though in some niches nothing else is viable, sadly.
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.)
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.
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.
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
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.
I'm not sure that this addresses my concern though. Do namespaces enable the import of specific symbols from a module?
https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.ht...
EDIT: I just learned module systems are NOT package managers.
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.
And your assumption that the lack of a package manager reduces bugs and bloat is based on what scientific proof? :-)
I said nothing of the kind! Obviously, that is not tenable at this time. But it's entirely possible to add a module system by which new code can take dependencies without the cumbersome #include mechanism.
It continues to deliver on the promise of providing the structure you want, without any undue runtime cost.
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...
Languages that break backwards compatibility tend to have very slow uptake of the new versions. Python 3.0 was released in 2008 and took at least a decade to become the main version. And the changes made to Python were minor compared to what would need to be done with C++.
> The language has become borderline impossible to reason about.
This I agree but mostly it doesn't affect casual users of the language. I drop into C++ every 5 years or so and I don't find it difficult to understand or be productive. I have no idea what the difference between glvalue, prvalue, xvalue, lvalue, or rvalue but it's mostly not a concern for me.
C++ certainly seems like a fragmented language from the outside. Lots of features added over the years to address problems with safety and provide additional "zero overhead" abstractions. The style and idioms of code written in this language seems to have changed pretty significantly over its lifespan. So breaking backwards compatibility to throw out old standards and force programmers to utilize new ones seems to make sense. However, it raises a few questions.
1) Who decides which parts of the language to throw out and which to keep? How do they decide this? Would the goal be to keep the multi-paradigm concepts, or re-focus the language? Which of the "zero overhead" abstractions should be kept?
2) Has this already been tried before in essence? There are certainly a number of languages out there that seem to strive to be "a better C/C++". What benefit is there to attempting to create a C++ 2.0 instead of using one of them?
3) Do the benefits of breaking backwards compatibility really outweigh the loss of all of the accumulated libraries and all the software of the past 30+ years? Even with ideal management of the new language, would it be enough to bring people to a new version?
4) Do you continue adding to this new version as you did with the previous one... surely that would eventually lead to the same fragmentation seen in the current version.
5) What happens to C++ 1.0 in this case? Do you continue to support and expand it? For how long? I suppose one could look at what happened with Python, but I'm not so sure it's that comparable.
Re: backwards compatibility, that's not really true. ABI compatibility is different than source-level compatibility. If a library or module is built to one language standard, so long as the ABI remains compatible, I think it's fair game to change syntax and semantics when compiling with a newer language release - especially when there's clear and obvious deficiencies in the existing. Obviously, the committee and I disagree on this.
However, my point remains that if you value backwards compatibility above all else, and it's that backwards compatibility that actually prevents you from adding features in a complete and honest way, maybe don't add the feature. Like, if `std::move` is the best you can muster, don't add it! It's not a move! I don't know what it is, but it's definitely not what the label on the tin says.
[1] https://thephd.github.io/your-c-compiler-and-standard-librar...
I mean, that's the point of them being "your own types". If you couldn't do anything that you want, including putting `assert(1 == 2)` in any method of your own type in C++... then people would be quick to design a Cwhatever language where you can, because it's a useful subspace of the design space of programming languages
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!
"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."
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.
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.
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.
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.
There are many features of C++ that would make a "better C", like namespaces and templates (which are better macros). But as good as they are in other contexts, smart-pointers are the last thing I want in C-like code.
Also, an advantage of C over C++ is that it doesn't have a runtime and it doesn't use name mangling. That makes linking much easier and particularly well suited to embedded applications.
If you have a program in "mostly C", you can start using RAII to manage your ressources. Then use std::unique_ptr, std::shared_ptr, and references instead of raw pointers. And namespaces. That already brings you to a very nice place without shifting completely to modern C++.
You don't have to use all the features of C++ if you don't need them.
Then the thing grows to a team of 20, and you find yourself applying restrictive rules about which subset of C++ is admissible, because otherwise everyone will consider a different subset for their own code.
"You don't need to use all of the language" is a false claim that doesn't go too far without adding extra friction to the project management.
extern "C" {
// my C++ code
}
Big deal.By the way, clang and Visual C runtime libraries are actually implemented in C++ with extern "C".
if I was using C++ to write business applications or something, like one would use C# or Java or whatever, then yeah, smart pointers seem like they would be useful in that specific domain... but at that point, why not just use one of those languages, or a language like it?
I'm probably going to try zig for my next endeavor into lower-level game development because that language, while different from the C-style-C++ I'm used to, seems much more in line with the kind of programming I'm looking to do, compared to modern C++. I don't want RAII, smart pointers, and all that conceptual overhead jazz. I want to allocate memory, run operations on said memory, then free said memory. I kinda miss just doing stuff in C89.
std::unique_ptr & std::shared_ptr are amazing. If you're still writing new & delete, you're just making things harder on yourself. I'll still use raw pointers in C++, but only the a borrowing context. It massively simplifies ownership. No more reading docs to try and guess if this pointer being passed in or returned needs to be freed or not. If I own it, it's a unique_ptr. If I'm giving it to someone else, it's a unique_ptr&&. If I'm letting something borrow it, it's a raw pointer or reference.
Or I'll make my own smart pointer containers for allocations with special lifecycles, like per-frame allocations from a custom arena allocation that must not be destroyed with delete/free.
Why try to remember all your lifecycle manually, which is incredibly error prone and no you're not immune to mistakes here, when you can compiler-enforce it instead?
There's basically no resource overhead for using the pointer abstractions that C++ offers.
Recall that the original comment was discussing whether to re-write something originally written in Python into C or C++.
Resource deallocation becomes extremely difficult in the context of (various types of) exception handling. C++ destructors make this a breeze.
Your expertise is laudable and am sure, hard won. The trouble is with expecting a larger team to buy into that philosophy.
Pragmatism beats dogmatism in practice.
No problem, but also little to no benefit. Why get in the habit of using them when you don't have to?
I didn't say "always use references", I said, never use raw pointers. Since shared_ptrs can be null, I don't see why this is a valid counterargument.
But these days I may prefer Rust over the two instead, if it’s not a numeric-heavy program.
* auto
* namespaces
* templates
* lambdas
The standard library is much more useful and expansive than C's.
And if you really care about performance, C++ is the obvious choice (but it does have its pitfalls, I think).
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.
STL containers and algorithms are the true gems from c++, paired with the speed and memory efficiency and smart-pointers, c++ is just getting stronger these days.
C++ is driven on all directions by a large number of very diverse stakeholders.
Doesn't 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.
> In each such definition
> However, g_s violates ODR because despite that there’s only one definition of it, there are still multiple declarations
Using real execution statistic to determine branch prediction (at compile time) should be the new standard
Like for instance, the class Button would need to implement the void Start(); function?
- 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!
* 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
* ...
I see 17 for some, a lot stuck at 11.
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.
The compiler knows that Addable<T> is a concept at this point right? Is the constexpr required?
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.
It's more than that - it can inform many optimisations, for example keeping values alive in one branch at the expense of another.
But see "Don’t use the [[likely]] or [[unlikely]] attributes": https://blog.aaronballman.com/2020/08/dont-use-the-likely-or...
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.
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).If you have arguments with the implementation that's one thing, but what would you prefer? That the language just stay still, warts and all? Ok... well then just keep using C++03. But you probably don't want to do that, because '03 sucks, right? Ok, and what would make it better? ----> All the things they're trying to fix via C'11 through C'20...
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.
That's often been true in other recent C++ standards, but looking at the linked page about C++20 in particular, quite a lot of those points might reasonably appear in application code.
If you don't need them (and you probably won't) then don't use them.
The trouble with this argument has always been that if your language provides a certain feature or syntax, even if you don't use it, there is no guarantee that everyone else whose code you depend on won't use it either.
Some language features are inherently contagious. If you are calling code that uses exceptions or const qualifiers or asynchronicity, you probably need to take that into account in your own code. I recognise that these aren't particularly esoteric as language features go, but I've still seen plenty of teams over the years that attempted to avoid using them in C++ based on some argument about making things too complicated, mostly with results that weren't great.
Even for new language features that are expected to be used mostly within libraries and not to be seen much in application code, you might still have to dig into the source code for a library to trace a bug or performance problem, which means in practice you still need enough awareness of the full language to do that.
Extra complexity in the design of a programming language always comes at a cost, whether or not you intend to use it. The important question is usually whether the price is worth paying.
No one ever forces you to use extra features. But if you can improve/reduce your code, why not?
I'm going to mark it off topic now, which will downweight it. In the meantime, please review the site guidelines: https://news.ycombinator.com/newsguidelines.html. They ask you to contact us at hn@ycombinator.com if you want to raise a question like this. They also ask you not to be snarky.
The core value of this site is intellectual curiosity, and divisive meta comments are not in that spirit. If other people are posting tediously and offtopically, the solution is definitely not to post tedious and offtopic comments with an oppositional vector. I know it's tempting, but it makes the threads worse. The solution is to post more comments in the spirit of curiosity, or (failing that) not to post.
You don't it has something to do with people being fed up with almost every other programming language thread getting spammed by low quality "meta" post about a certain language superiority which are irrelevant to the discussion?
Have no idea how to solve that. I have never moderated online communities and that’s not my area of expertise.
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 :-)
"Oh, 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."