22 ms·
C++ 20: The Core Language
- CoolGuySteve 7y agoHopefully between consteval and string literal template parameters, we'll be able to detect literal const char* in templates. Would be nice for my threaded logger to know if it can copy the pointer instead of the whole string, knowing it was initialized statically.
- MaxBarraclough 7y agoWouldn't the ideal solution involve the const system?
- glouwbug 7y agoDid modules make it?
- steveklabnik 7y agoYes, they did.
- lasagnaphil 7y agoRight now my biggest things I like from C++20 are: - Concepts (Now I can use static polymorphism without all those SFINAE template hacks) - Designated Initializers (Finally!!! Using POD structs became way more convenient now) - Coroutines (Would be pretty nice for writing games / interactive applications) The things I don't have any interest in (but don't care if it's in or not) - Ranges (Too much complexity for something you could do with plain old for/if loops...) The things I'm worried about: - Modules (Theoretically really good, but in practice the whole thing is starting to become a mess, especially when it's interacting with the preprocessor and external libraries, and when trying to preserve backward compatibility.)
- jokoon 7y agoI have hope for modules because they can improve build times. Not exactly sure they would improve build time but if it's true, it would be a massive improvement.
- Renana 7y agoHave you tried using IncrediBuild. It's a dedicated solution to reduce C++ build times. If you're working on Windows, you can use it free (sharing the link to download): https://www.incredibuild.com/ibonlinestore/register#/regWindows?utm_source=hackernews&utm_medium=question&utm_campaign=answer&utm_content=download https://www.incredibuild.com/ibonlinestore/register#/regWind...
- saurik 7y agoMeanwhile, I am deeply concerned about modules, as it seems like the kind of feature that is going to massively harm build times by making it much more difficult to do truly independent distributed builds (which right now is pretty easy with C/C++ due to its separate compilation and extremely explicit inter-file dependencies).
- vips7L 7y agoWasn't the point of modules to decrease compilation/build times?
- saurik 7y agoSome claim this, but I haven't seen it play out this way yet in what I have seen for modules; it could be that people are hyper-optimizing for serial performance when the future (and present!) is parallel? If so, :(. This article is possibly out of date--or maybe was wrong to begin with--but it shows how the modules concept from earlier this year simply broke parallel build efforts by enforcing a ton of serial dependencies. https://vector-of-bool.github.io/2019/01/27/modules-doa.html https://vector-of-bool.github.io/2019/01/27/modules-doa.html
- DeepYogurt 7y agoI'm not sure I grok the `<=>` operator and the example they show seems to just show that `a == b`. Can someone explain what's going on with that?
- htfy96 7y agoPreviously you need to override all six operators (==, <=, <, >, >=, !=) to provide total order comparators. Now you only need to provide one method.
- bleair 7y agoHtfy96 is right. This post gives more examples. https://devblogs.microsoft.com/cppblog/simplify-your-code-with-rocket-science-c20s-spaceship-operator/ https://devblogs.microsoft.com/cppblog/simplify-your-code-wi... Along with automatic synthesis of all the operators, c++ 20 also clarified rules about overload-matching and automatic construction of objects for purposes of comparison, so you don’t have to write the friend methods to for example compare int to your type if you have trivial int-taking constructor for your type. Also if your == operator or != is more efficient than a full lexigrapgical comparison the compiler will now do the right thing
- inetknght 7y ago> I'm not sure I grok the `<=>` operator Think of `strcmp` which returns an int. The int can be <0, ==0, or >0. That same `strcmp` can then be used to implement all other standard comparison functions. `operator <=>` is the generalized version of that.
- johannes1234321 7y agoAn important part there is: Most users will never call <=> themselves. However somebody implementing a type can implement a single function and the compiler will translate usage of <, <=, ==, !=< >=, > to the single function. Reduces boiler plate in the implementation. (Think about it - most implementations of > or < will often use the same logic already, spelling this out is "annoying"; mind that for performance reasons it can still be worthwhile to implement a == explicitly as equal comparison is often faster than ordering, but that's something the type designer can chose)
- DoofusOfDeath 7y agoIn commercial settings, I encounter several barriers to using C++ versions newer than 2011: (1) Most C++ code I encounter is C++11, and I deal with lots of projects. It's rarely sensible to change the language version of a large code base without a very good reason. (2) Many developers are well-familiar with C++11. (3) There's no widespread perception that C++14 or later bring compelling language improvements. (4) Some (most?) C++11 developers are already uneasy with the complexity of C++11, and aren't eager to incur the learning curve and (perhaps) new set of pitfalls associated with newer C++ versions. (5) Some C++11 developers look at the language trajectory, especially in terms of complexity, and have decided that their next language(s) will be e.g. Rust or Julia instead of C++14, C++17, etc. I suspect these factors all contribute to the momentum that C++11 seems to have.
- w-m 7y agoOn the other hand, there aren't really any changes in 14 and 17 that break compatibility with code written in 11, at least that I'm aware of. In the examples I've seen it seems to mostly come down to compiler, toolchain and 3rd party binary availability for the new versions, like with any major language version. If for example you are using stock gcc from Ubuntu 16.04 for your builds, you can't use C++17.
- Fronzie 7y agoFor big (legacy) code-bases, just upgrading the compiler is a project by itself. All 3rd party C++ libs need to be upgraded, all internal projects need to upgrade in an orderly fashion. On top of that, just the change of the compiler will expose some pre-existing bugs.The bugs might have been there, but are not a problem for the business if they currently don't show. I've seen projects with a core team of half a dozen people, supported by the other SW engineers working for 6 months just to upgrade to a newer version of windows and the compiler. This was mostly due to unwise SW-design decisions accumulated over 15+ years.
- w-m 7y agoI totally agree, updating compilers is painful, and can be hard even for smaller projects. But for projects that went through that and actually got the newer compiler working with the C++11 code, I haven't yet seen anything that breaks compilation when then switching the compiler flag to C++14 mode.
- gumby 7y agoOn thing I appreciate is mdspan -- multidimensional projections onto a regular linear vector. I've always had to spin these myself which means they don't fully participate as ordinary containers (who's going to go tho all that work for their own application code). I'm hoping I can map them into GPU space -- looks like the standard has adequate control for this.
- alexhutcheson 7y agoDoes Eigen not work for your use cases?
- gumby 7y agoThat's a good call for a great library. It's often overkill for what I do, especially as it can't use the same compiler options as my tree normally does (they have to bend over backwards for back compatibility; I don't). I do use it some places. I certainly don't envy the hard work of library developers! When I simply need a 2D or 3D resizable array it's often easier, as I mentioned, to simply spin one up. Having that support "native" will be great.
- zelly 7y agomdspan didn't make it in 20
- gumby 7y agoRats!
- dgellow 7y agoCould someone describes the keyword "unlikely" and "likely" in a bit more details? It seem to be a very niche thing to add to the language. Is it expected that those hints will have an impact important enough regarding what the optimizer can do?
- zarkov99 7y agoWithout actually looking at the docs, I would guess these map directly to cpu intrisics that can be used to guide the cpu branch prediction algorithms.
- harry8 7y agoWhich cpu instructions guide branch prediction algorithms? Which cpus?
- gpderetta 7y agoAt some point pentium4 had static branch prediction hints, but they are obsolete and no longer relevant. Today __buitin_expect are mostly used to mark hot/cold branches. The compiler will normally optimize hot code for speed and cold code for size also will attempt to put cold code in separate cachelines and even pages. And other similar code layout optimizations.
- johannes1234321 7y agolikely and unlikely exist in different forms as compiler extensions for a while. There is code where they indeed help compilers to produce slightly better code for the hot path. Good use typically involves lots of measurement as developers are often wrong about the impact and about what the real flow is. What kind of things can the compiler improve? For instance it can arrange the code in a way that the instructions of the hot path are directly behind each other, whereas the unlikely case jumps further away. Or it can arrange code a bit to help the branch predictor.
- usefulcat 7y agogcc and clang (at least, I don't know about msvc) have had these for a while. Basically, the instructions for whichever branch is declared most likely to be taken will be placed immediately after the comparison instruction(s), which is generally more cache-friendly. It seems conceivable that it might also affect the compiler's inlining choices in each branch (i.e. don't bother to inline as aggressively in the less likely branch, to reduce code size), though I don't know for sure.
- gumby 7y agoI'm glad this hasn't turned into (so far) the usual "c++ is dumb" flame fest. I've really enjoyed programming in c++17 for the last three years (I had the luxury of starting from an empty buffer) and find the language pretty expressive. If you are able to use it as a "new" language, ignoring its C roots and features that exist pretty much just for back compatibility, it's really quite expressive, powerful, and orthogonal. I'm actually pretty glad the c++ committee has been willing to acknowledge and deprecate mistakes (e.g. auto_ptr), to squeeze out special cases (e.g. comma in subscripting) and to attempt to maintain generality. Conservatism on things like the graphics standard is reducing the chance of the auto_ptr or std::map mistakes.
- fnord77 7y agolast time I used C++ was in the mid-2000s. With all the new features since then, I assume the "proper" way/style to right C++ has changed since then?
- gumby 7y agoI don't know if you mean formatting, in which case I don't believe anything has changed (pretty much anything goes) but yes, you can now do for (auto [x, y] : list_of_coordinates()) ... and things like that.
- gameswithgo 7y ago* is now deprecated.
- gumby 7y agoNot formally, but as you were responding to a comment on style: indeed, you don't really need * that often; there are more powerful, safer options in most cases. But C++ is a systems programming language and * is still quite useful.
- CodeMage 7y agoThis is not even remotely true. Let's say you have: std::unique_ptr<foo> m_foo; How do you pass that into a function that can receive a pointer to foo, but does not require it? The only way to do so is to declare the function to take a foo* and pass it m_foo.get() In summary, * will never be deprecated until C++ has support for something along the lines of Rust's borrowing and lifetimes.
- Ididntdothis 7y agoI haven’t done C++ a while but I really like where this is going. It’s a complex language for sure but I always liked about it that whatever needed to be done the language would not get in the way. There is something to be said for working in the language your OS and a lot of other libraries are written with. You know that you have high probability of achieving what you need to do. It may need a lot of work though.
- gumby 7y agoWith consteval (and its cousins), std::source_location and modules you could pretty much compile C++ without the preprocessor. Hooray!
- DerekL 7y agoThere's still the need for logging and assertion functions, where you want to test the debugging level or some other value before you evaluate the arguments to the function. Right now, you need to use a macro, but there's a proposal: James Dennett and Geoff Romer. P0927R2: Towards A (Lazy) Forwarding Mechanism for C++. ISO/IEC C++ Standards Committee Paper. 2018. url: https://wg21.link/p0927r2 https://wg21.link/p0927r2.
- beezle 7y agoBeen away from C++ a long time. If picking it up again, is it better to just start with C++17 or 20 or stick to C++11 which seems to be the defacto production version?
- gumby 7y agoDepends on your needs. If you don't have a lot of or any legacy code yes, go straight to c++17 (or even 20 though you won't be able to use many of the features right out of a the gate, or without third-party libraries). If you can do this you'll be glad you did. I was able to start a project in c++17 in 2016, though at the time I had to use boost::variant with the Xcode compiler and boost::filesystem for all three compilers (only a limited use so I could even have skipped it). Also for some complex third party libraries I had to make a little trampoline file that compiled in C++14, or with special flags, and then call those entry points. Since I was starting from a blank slate I also compiled everything with pretty much maximal warnings an -Werror which really improved the code a lot, something you can never get away with with legacy code (not to insult working legacy codebases!)
- kllrnohj 7y agoC++11 was the major version bump. It changed how you're supposed to write C++. C++14 & 17 are just minor fixes & improvements. So there's really no reason to not start with at least C++17.
- gridlockd 7y agoWhy 'basic_fixed_string'? Is it really so basic that it has to be mentioned in the name? Is it just in case there might be a 'fixed_string' that isn't quite as basic, in the future?
- jcelerier 7y agofor the same reason that std::string is std::basic_string<char>
- harry8 7y agoOk. And what reason is that?
- rightbyte 7y agostring is a typedef of the template basic_string so you don't have to type as much I assume.
- axilmar 7y agoIt would be nice if this worked: template <class T = char> class string { ... }; string s = "a";
- rightbyte 7y agoIt does with newer compilers. Was some bugs with gcc and clang earlier. Try: #include <cstdio> template <class T = char> class string { public: string(const T *const c) : c_ptr(c){} const T *const c_ptr; }; int main() { string s = "qwe"; printf("%s", s.c_ptr); return 0; }
- jcelerier 7y agowhat would you do instead ? surely you would not have std::string be a template directly and type std::string<char> / std::string<wchar_t> instead of std::string / std::wstring every time you want a string ?
- afranchuk 7y agoI've been anxiously awaiting modules and concepts. Both are incredibly important to reduce developer burden and improve the development experience. Modules: While it is important to be able to fine-tune linking and compilation in some settings, in most, and especially for beginners, this should be handled by the compiler. Especially when compared to other modern languages, C++ is much more complex to understand the toolchain and what's going on under the covers with the dichotomy of compilation and linking. Header files were a hack that have been around for too long, and there needs to be less separation between the interface and actual binary code when compiling. This is a headache both for novices and the experienced. Concepts: The missing link for templates. Besides removing some of the roundabout-ism of SFINAE by providing compile-time verifiable interfaces, I think the biggest benefit of concepts will be the error messages. Right now, the state of errors in heavily templated code is abysmal, and this translates to a lot of wasted time for developers. Concepts should allow the errors to indicate exactly what's wrong. I can't wait to be able to use these in public code. Some compilers support concepts with a flag already (and GCC 10 has it without the special flag), though none support modules yet...
- EamonnMR 7y agoAre there any quality tutorials for learning C++17 for basic tasks? Much "how do I do X in C++" is very outdated from that perspective.
- lone_haxx0r 7y agoI haven't read it yet, but No Starch published "C++ crash course" a month ago, which teaches C++17 and looks appropriate for what you ask. https://nostarch.com/cppcrashcourse https://nostarch.com/cppcrashcourse
- sharpneli 7y agoSome parts of C++20 are really good, like most of what is stated in the article. But C++ would not be C++ if it had no shenanigans coming. Unless they have changed things within some months the new calendar/datetime library is hilarious. It has features like being able to write a date like: 1/2/2000y. ooh fancy operatoe overloading. Which one is month? The first one ofcourse as it they didn’t standardize on any of the existing ISO standards, or allow you to choose, but selected ”Customary US way” as the Only True C++ Way(tm). Also do not forget the abuse of operator overloading like in the good 90’s when misusing it was the recommended thing.
- vbezhenar 7y agoWhy not something like Date.of(2000, 2, 1)? Much more sane. Or Date.ofYear(2000).month(2).day(1) for more descriptive usage.
- alexhutcheson 7y agoFWIW the absl CivilTime library is excellent: https://abseil.io/blog/20181010-civil-time https://abseil.io/blog/20181010-civil-time
- gpderetta 7y agoAs far as I can tell from cppreference (I literally found out about the datetime extension to chrono right now), your example won't come mobile because it is ambiguous.
- lacampbell 7y agoWhat are people using C++ for in 2019? Last time I used it was for a Qt desktop application of all things. I would imagine its main usage is in high performance or hardware constrained environments these days, but I'm curious what people are doing with it. I do a lot of node.js programming, which uses C++ to write extensions, so here's hoping I rememeber it if/when I need to.
- gpderetta 7y agoWell, apparently it is pretty good to write VMs for other languages.
- zelly 7y agohigh frequency trading, AAA video games, aerospace, compilers, audio, self-driving cars, search engines, subways If it's important, it's using C++.
- gpderetta 7y agoSubways?!? Tell me more!
- missblit 7y agoWhy I'm using it to write a Qt desktop program of course. Actually a bit frustrating, since Qt is very opinionated in a way that hasn't aged well with newer C++ standards, but it is probably one of the best cross platform UI libraries.
- rosshemsley 7y agoFeatures I wish C++20 had: * An opinionated, modern packaging and dependency story (like go modules, Rust crates) * built-in library support for logging, http, zip, gzip, json, yaml, template rendering, RFC3339 datetime reading/writing * the dream: compliant compilers must be able to compile down to static binaries, cross compiling built-in. Features C++20 actually has: * new fancy spaceship operator that I'll now have to learn and never use...
- zelly 7y ago> built-in library support for logging, http, zip, gzip, json, yaml, template rendering, RFC3339 datetime reading/writing There is a Boost library for each of those things. > An opinionated, modern packaging and dependency story (like go modules, Rust crates) > the dream: compliant compilers must be able to compile down to static binaries, cross compiling built-in. You can use Conan or vcpkg. LLVM basically solves the cross-compiling issue since you can take the IR to any platform that has a LLVM target. Neither of these are feasible to include in the International Standard because C++ runs on more than amd64 and would make a lot of obscure platforms no longer compliant with the standard. Rust crates are nice, but people building medical devices with C++ shouldn't need to worry about supporting an npm-like monstrosity in their builds.
- steveklabnik 7y agoLLVM IR is not platform independent. Rust compiles on far more platforms than amd64, and Cargo works just fine. Nothing forces you to depend on any packages you don’t want to.
- zelly 7y ago> Nothing forces you to depend on any packages you don’t want to. Nothing stops you, either, which is a problem for everyone in the future who uses your code. The first reaction to any problem in JavaScript/webdev is to google for a library to import to solve the problem. This is acceptable behavior because the existence of a web browser implies powerful enough resources to accommodate bloat. But this mentality isn't acceptable on other systems and has even infected some basic functionality: https://crates.io/crates/rand https://crates.io/crates/rand The random number generator for Rust has 6 dependencies. In C++, it's only lib[std]c++. In Java, it's java.base.
- eyegor 7y agoIs there a good "tutorial for modern c++" resource out there? The last c++ I used heavily was c03 and a sprinkle of c11. I find reading modern c++ to be somewhere between frustrating and an exercise in hieroglyphics thanks to how much it's changed. Something along the lines of "basics of why to use the different std pointers/views instead of raw pointers", lambdas, all the new const-like bits, and whatever else have become "core" features.
- karmicthreat 7y agoI've read "A Tour of C++" by Stroustrup. It was helpful in trying to catch up to modern idioms for C++.
- mhh__ 7y agoScott Meyers's books, although I think they stop at C++14 will get you up to speed
- xvilka 7y agoC++ should adopt Rust-like approach on deprecating things faster and a tools like `cargo fix`/`cargo clippy --autofix` to automatically fix/suggest more modern alternative to the deprecated language constructions.
- AllanHoustonSt 7y agoThere’s an initiative for Rust-like editions, but I think it’s a controversial topic within the C++ committee.
- shaklee3 7y agoThis book is worth checking out if you don't know c++17: https://www.bfilipek.com/2018/08/cpp17indetail.html?m=1 https://www.bfilipek.com/2018/08/cpp17indetail.html?m=1 That guy has a great blog where he writes at length about each feature, and the book is a compilation of that.