12 ms·
Has anyone anything positive to say about C++, and more specifically C++20? We all know the negative parts, any C++ related thread is always full of people rep
by dgellow 6y ago
Has anyone anything positive to say about C++, and more specifically C++20?
We all know the negative parts, any C++ related thread is always full of people repeating them over and over. What about some celebration time for now? A huge milestone for the language has been reached with C++20, can we share something positive about it for once?
- jzwinck 6y agoYes! The spaceship operator (three way comparison a la strcmp) is very welcome, and the no_unique_address attribute will be helpful for people who care a lot about optimization. Simplifications like these really help, and don't take a programming language genius to utilize.
- AlexSW 6y agoAs someone that really likes C++ templates (no other language seems to come close in power for such a compile-time typed system), I'm particularly looking forward to concepts, and I believe (correct me if I'm wrong) that they will make compiler errors for templated code much more straightforward, which will be a nice quality of life improvement even if not using concepts directly.
- greggman3 6y agoThat strikes me as Stockholm Syndrome. No one in their right mind would consider C++ templates a good design for a meta-language. In fact the majority of older template patterns aren't based on good language design but hacks around conditional compiling via arrays of size -1 and crap like that. A good meta programming language would be one that's as easy to program as a general language. lisp, nim, etc...
- einpoklum 6y agoIt's true the templates weren't designed as a meta language. C++ has a lot of baggage. But, at least, you no longer have to iterate over arrays with size-1, (size-1)-1 etc these days. We have variadic template expansion, we have the (ugly, still not decent design, but useful) std::integer_sequence , and better still - we have pretty strong constexpr capabilities.
- Expert-007 6y agoSuch examples speak more to C++ templates as a mechanism for capturing usage patterns in a convenient form, thus effectively creating a special-purpose, domain-specific language, than they speak to such templates as a meta-language. "Meta" means "information about information", so a meta-language in this case would describe the mechanisms used to capture such patterns, not the patterns themselves. I do meta every day, meta-meta often, and triple-meta occasionally. The rules language for my Expert System is a true meta-language, because I designed it to (among other things) specify the manipulation of computer languages. So its domain knowledge is about the nature of computer languages and how to automate their assessment / analysis, transformation / re-engineering, translation, and generation. To give a real-life example, we used our Expert System to automate the translation of complex compiler front- and back-end code from a proprietary system language to C++ for a major computer manufacturer. The translation rules don't really care what the code is doing; they care how the code is doing it. The compiler team created new templates and classes to provide the functionality their system language had that C++ doesn't, and we adjusted our translation rules to ensure that the translated code invokes those templates and classes in a clear, effective, efficient, and readable way.
- HelloNurse 6y agoExactly, old hacks and techniques. Thirty years ago, C++ template were limited and clever people struggled with their limitations, but now there are vastly simpler ways to do much more.
- _se 6y agoI think this is.. quite wrong. I don't think C++ is an amazing language (it's not in my top 3 personally, but I do work with it daily), but templates are one of the best things about the language IMO. I have a lot of experience with many different types of metaprogramming (cl macros, Rust macros, template Haskell (and Typeable/Generic), ... even CLR code generation) and C++ templates are better than everything I've used other than Common Lisp once you really understand them. A really common C++ theme I see is people that don't understand things railing against them (I used to be in this camp myself, so I can identify with the sentiment). Templates allow you to choose at will between nominal/structural subtyping (in a way), perform type-level logic, generate code that can be thread-safe or lock-free at the caller's whim... They are very powerful, much more than most devs realize, and if you understand C++, writing them is not difficult. The "really understand them" part is, of course, the hard part. You need to understand the core language and the template language to be effective with them. I can see why even some experienced C++ developers shy away from templates.
- Dylan16807 6y agoEven if they're a good general design, half the uses of SFINAE are absolutely insane and from what I understand it's significantly harder than it should be to make a fully generic template across all kinds of edge case and corner case types. The attitude with templates seems to be that if something is at all possible with hacks then there doesn't need to be any language support added, even if it would be vastly simpler to read and write and probably to compile. I don't think that works out well.
- northwindfoo 6y agoI wouldn't call myself a c++ expert but I have used the language for a long time. In my opinion, templates have a lot of awesome uses outside of SFINAE and if you find yourself reaching for SFINAE, that's probably code smell and you can probably simplify the design elsewhere to avoid it. Generally I find the best use of templates is the most basic: you want to write some code that operates on duck-types. As long as one is able to control themselves and pick the right use cases for maintainability, templates are simple enough. In my experience, this is very doable. Concepts are also a really cool way to rein in which types are accepted as a template parameter and have a lot of potential to make templates easier to understand and teach. To me, this is the most exciting c++20 feature.
- otabdeveloper4 6y ago> ... easy to program as a general language. lisp, nim, etc... C++ templates are just a compile-time lazily-evaluated Lisp. As always, the criticism of C++ comes down to "programming is hard, let's go shopping". If you don't want to learn and you just want to do the bare minimum to keep your 8 hour coding job, there's already plenty of languages that nail this niche. C++ obviously is not for you, just move on and don't make a redundant comment.
- greggman3 6y agoWhat an asinine comment. I guess if you're real programmer you'll program everything in brainfuck. Isn't not hard to fathom that some language designs are easier to express and easier to understand than others and still get the same things done. C++'s meta programming via templates is clearly a hack and was never designed to do what it's being abused to do.
- zarkov99 6y agoOther than lisp, which production ready languages do you think do it better?
- rwmj 6y agoI really liked camlp4 (an early fork of which is available as camlp5, but no longer a fundamental part of the OCaml ecosystem). I was able to use camlp4 to implement Erlang-style bitstrings, and they were as efficient as if you had written the most efficient code by hand. https://people.redhat.com/~rjones/bitstring/html/Bitstring.html https://people.redhat.com/~rjones/bitstring/html/Bitstring.h...
- SloopJon 6y agoI consciously avoided C++ since the late 90s, lest its litany of accidental complexities crowd other more important things out of my brain. I was drawn into it recently by a work assignment, and have been pleasantly surprised by modern C++. I find it much more pleasant to write, e.g., ODBC client code in C++ than in C, and templates have a lot to do with that. I'm not an expert with Lisp macros or other reportedly superior meta-languages, but I will say that when I write generic code in C# or Java, I really miss the power of C++ templates. Template syntax is pretty awful, and accomplishing what I want can involve some really strange idioms, like SFINAE. The ergonomics are slowly improving with type deduction, constexpr, and now concepts.
- gumby 6y agoAs Stroustrup said to me years ago, “yes, I wanted a macro system but that word had already been colonized by the preprocessor, and we needed to avoid new keywords as much as possible if people were going to try it out. Nowadays C++ and a powerful multi-paradigm programming language quite straightforward to use if you forget the word “C” in its name. If would be a good instructional language if people didn’t fall into the lazy “a horse is a king of animal” OO trope.
- dgellow 6y ago> I believe (correct me if I'm wrong) that they will make compiler errors for templated code much more straightforward Oh yes, that would really be awesome if that's the case. Wikipedia has a section regarding "Compiler diagnostics" when Concepts are used, the precision of the error message demonstrated is SO MUCH better than what you get with templates! https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)#Compiler_diagnostics https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)#Compiler_di... Code example: std::list<int> l = {2, 1, 3}; std::sort(l.begin(), l.end()); Example with templates: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]': error: no match for 'operator-' (operand types are 'std::_List_iterator<int>' and 'std::_List_iterator<int>') std::__lg(__last - __first) * 2, ... ... // continues for 50+ lines Example with concepts: error: cannot call function 'void std::sort(_RAIter, _RAIter) [with _RAIter = std::_List_iterator<int>]' note: concept 'RandomAccessIterator()' was not satisfied
- HelloNurse 6y agoStraightforward error messages are only an aspect of straightforward template definitions: the problem of restricting templates to suitable type parameters has the first general, explicit and well organized solution.
- mhh__ 6y ago> no other language seems to come close in power for such a compile-time typed system D is far more powerful, especially when you consider that it's had working constraints for (?) something like a decade now. Simple example, try to express this in C++ without a windows full of syntax-soup (https://d.godbolt.org/z/Toc8ob https://d.godbolt.org/z/Toc8ob), the template constraint is one line, and I can pass anything into a template using alias be that templates, a string etc. Passing strings into a templates is a very common trick for generating code at compile time in the D standard library, although it wouldn't work in C++ due to how slow C++ can be to compile some times.
- pjmlp 6y agoSadly, D the language still needs to get their act together in what the language actually wants to be, and the eco-system suffers from this lack of direction.
- nikki93 6y ago> Passing strings into a templates ... wouldn't work in C++ ... https://www.youtube.com/watch?v=QM3W36COnE4 https://www.youtube.com/watch?v=QM3W36COnE4 Here's an example of parsing regular expressions in C++ at compile time. Code here: https://github.com/hanickadot/compile-time-regular-expressions https://github.com/hanickadot/compile-time-regular-expressio...
- ainar-g 6y agoIf you use a tiny subset of C++, then you get a dialect of C with more type safety, namespaces, mostly-not-unsafe subtype polymorphism through class inheritance, and also okay parametric polymorphism through templates. That dialect will compile a bit slower (it's still C++ after all), but produce code which either has the same performance as C or is only slightly behind C.
- shash 6y agoOr often, faster than C, if you’re using compile time template expansion instead of runtime void* casts.
- einpoklum 6y agoYes, I have many positive things to say about C++. It certainly has a lot of warts, but over the past decade, it has become easier and more straightforward to write code in various styles which used to be possible-but-a-pain (like functional programming), or not quite possible. So with C++ you get performance + backwards compatibility + paradigm flexibility for the price of difficult, sometimes ambiguous syntax, some historical baggage you need to ignore, and slower compilation time. It's a decent tradeoff IMHO. Specifically, regarding C++20: * std::span is the best thing since sliced bread. How was this not in the library already? Cuh-razee... https://stackoverflow.com/q/45723819/1593077 https://stackoverflow.com/q/45723819/1593077 * I'm happy that ranges support is inside the language. I can now `sort(my_container)` rather than the clunky `sort(my_container.begin(), my_container.end())` for example. And there are a bunch of useful lazily-evaluted range views. I only wish more of the ranges library could have been added. And I hope the compilation of ranges isn't too slow. * Modules can now start replacing include files. Initially, this will only be a theoretical possibility, but within several years, no longer will your compiler have to deal with 100,000 lines of text or so per translation unit: It will be like in Java and other languages, where it's just your current file that needs to be compiled and the rest is already compiled. Of course the transition will not be smooth (feature macros, conditional compilation - not obvious to me how to replace them when using modules), but this is a good direction. We could see faster compilation times and content suggestions in IDEs. * Expanded constexpr support means we can do more work once, at compile time, rather than repeating it at run-time (e.g. dynamic memory allocation - so you can have constexpr std::vector). * Coroutines are something interesting which I am not familiar with (except the very rough general idea of different control flows being switched between. I can at least say it's interesting to look into. * libfmt string formatting - Yes, yet another way to format strings: printf-style, iostreams, and now the "Python style", I guess you could say? It combines some benefits of both of the previous ones. * std::source_location - you know how, if you're writing some error-handling function, you usually need to wrap it in a macro which gives you the filename and line number? Well, that's going away now. I know it's just a minor thing, but I hate having those macro'd error handlers. * You can now tell the compiler to use a generated equality and comparison operators; this saves you boilerplate. Although in the C++ tradition, this capability is defined in a somewhat convoluted way under the hood.
- 6y ago
- foxtacles 6y agoYeah, it's unfortunate! I love C++ personally, I've recently commented something positive in another thread: https://news.ycombinator.com/item?id=24041406 https://news.ycombinator.com/item?id=24041406
- pdpi 6y agoPointer types in C can mean a bazillion different things, and C++ provides you with zero cost abstractions to unambiguously represent many of the useful ones (references vs owned pointers vs shared pointers vs arrays, off the top of my head), that alone makes it worth the price of admission for me. RAII is a damned useful idiom too, makes writing safe code that much easier. Tooling for C++ is pretty damn good in all the usual platforms
- virgilp 6y agoThey are not zero-cost, but yes, it's good that they were added
- vlovich123 6y agounique_ptr isn’t 0-cost?
- vvanders 6y agoshared_ptr certainly isn't, last I looked at it there was some significant performance overhead since it's required to be thread safe.
- gumby 6y agoYes but imagine writing thread safe refcounted GC in C. It’s painful and easy to forget some of the handshaking. Most of the abstractions (E.g. iterations) are zero cost as opposed to additional functionality like shared pointers or resizable vectors.
- pdpi 6y agoWhether shared_ptr are thread safe is an... interesting question. If you have to ask it the answer is “no”. At any rate, the definition of “zero cost” isn’t “it’s the same as a raw pointer”. Rather, it should be read as “its cost is the same as the equivalent functionality rolled by hand”. Shared_ptr implements a ref counting mechanism, which, absent a real GC, is necessary for actual shared ownership.
- UncleMeat 6y ago> Has anyone anything positive to say about C++ IMO, C++ has the following huge benefits. 1. Ambient performance. If you need a fast program and don't have a tight loop you can optimize, C++ makes ordinary behavior fast. 2. RAII is a very clean and understandable design paradigm. 3. The idiom of using "const" everywhere plus widespread copying of values makes "spooky action at a distance" way less common when doing OOP or imperative programming.
- asdfasgasdgasdg 6y agoLooking forward to having access to coroutines. Also the <=> operator and ranges. Lots of really good stuff in this release.
- snarfy 6y agoI did C++ for 10 years before moving on to C# for the next 10. I had an opportunity to work on a modern C++ project for a couple years and took it so that I could learn the new stuff. The team lead was a big C++ fan and used all the latest features with compiler set to c++17 standard. I could go on about the bad parts, but the good parts 1. lambdas 2. constexpr 3. threads These additions did make C++ feel a little more modern.
- shultays 6y agoIt is a performant language that is relatively safe when you use safe practices. And quite mature with lots of library support
- pjmlp 6y agoPlenty, Finally we got modules, concepts will put an end to the fame of endless kilometres of error messages and compile time programming almost allows for static reflection.
- nikki93 6y agoI'd written C++ a bunch around 2006-2011 for gamedev, and jumped back into it recently and am really really loving it. I had a while in between of leaning into C which I think is important to do, to move away from the super OO based approach which I think C++ isn't necessarily about anymore. Highlights for me: - Type deduction -- basically using auto for variable declarations. - Move semantics makes RAII actually usable since you can make heavy / important objects but then move them elsewhere and still have their lifetime be automatically managed. I use this in my game engine to wrap physics bodies etc. so that they are automatically removed from the scene when the component containing them is dropped (I'm using an ECS). A neat thing also is you can delete copy constructors and force certain types to be "move-only." - Having been in C-land for a bit, I'm appreciating the ready availability of std::vector and std::string again. Also std::array is awesome. - Lambdas are amazing. I often make simple control structure utilities in my modules that accept lambdas, and they are often inlined. I don't often do lambdas where I 'save them and call them later' -- they are mostly immediately called. This makes it safe to use reference captures. As for C++20 I am mostly interested in seeing how it goes with modules Also the `requires` keyword will simplify some of my uses of `enable_if`. A lot of the good stuff is also due to ecosystem and tooling vs. just language. My game works everywhere now: native macOS, Windows and iOS, but especially web due to Wasm! It also has an immediate mode API for rendering UI in Wasm, which I use along with some simple reflection to get an automatic entity inspector: https://m.imgur.com/dyUtL8f https://m.imgur.com/dyUtL8f The entire gameplay code fits in like 700 lines: https://gist.github.com/nikki93/5893543a5e3d76a7858d54b74a4c1a16#file-main-cc https://gist.github.com/nikki93/5893543a5e3d76a7858d54b74a4c... You can see how I don't do any pointer stuff or manual recource / memory management there at all. Tbh in many cases with precompiled headers it almost feels like it builds about as fast as webpack. And then my "publish" is a simple rsync of static files to the server. Another tooling / ecosystem thing lately has been godbolt.org which is wonderful for seeing immediately the asm that ur code generates. Which then makes you realize how good optimizing compilers for C++ are these days. I don't think other languages have come so far. And then with godbolt.org you can learn which constructs produce what code. I'm using entt for the ECS: https://github.com/skypjack/entt https://github.com/skypjack/entt you can see how it encourages the use of POD structs and non-OO code for the most part. It feels good to use C++ in that style as a C with the above features. I just basically don't use vtables / RTTI anymore. I do use templates a fair amount. I do concede that this enthusiasm may have a lot to do with having had experience in C/C++ already for a while. If I was completely new to the language it'd be a lot harder. The backwards compatibility lets me keep all my experience (even if the point isn't to write exactly like how I wrote before, but to understand the motivation for the new features). I've also dug into Go, Rust, Nim, Common Lisp, Haskell, ... but weirdly modern C++ has been the best combination of ergonomics, control, and portability. Especially for Wasm you really just want deterministic resource management. I'd probably still combine it with Lua or JS for scripting eventually. You do have to invest a lot of energy into learning the language and caring about the details, but I think C++ is very well positioned to reward you for that investment, and you are also rewarded continuously and early.
- creativeCak3 6y agoHave been using it professionally for a little bit now. -RAII -Smart Pointers -Classes(or not, your choice) -Lambda Expressions -Amazing Standard Library -Lightning fast -A compiler that you can trust -Static types -Templates -Well defined semantics for pointers, references AND values. -Moving semantics. And this is the "Vanilla" version of the features. In C++17 and C++20, there is all kinds of goodies like concepts and modules that I'm personally excited about. Hate it all you want, but it's an amazing language.
- atombender 6y agoI love the new modules. In fact, it's the one major feature I'd love to start using right away that I know would be immediately useful, but the compiler support isn't there yet. According to this [1], Clang has partial support [2], while GCC has no support at all. [1] https://en.cppreference.com/w/cpp/compiler_support https://en.cppreference.com/w/cpp/compiler_support [2] https://clang.llvm.org/cxx_status.html https://clang.llvm.org/cxx_status.html
- spacechild1 6y agoI am mostly writing audio applications where I need maximum performance because the time budget is extremely limited (usually 1.45 ms to compute the whole audio graph). I'm working on Pure Data, which is written in C89, but my own projects are all C++. Things which make C++ much more pleasant than C: * RAII * lambdas * templates * function overloading * operator overloading (used judiciously) * inheritance and interfaces (used judiciously) * an extensive standard library * exceptions (depends on the project) For me, the advantages of C++ over C are obvious and IMO there's no reason to use C except for legacy projects or platforms which don't have a C++ compiler. Of course, C++ has lots of warts and things to complain about, but OP asked for the positive things :-)
- pjmlp 6y agoMany of those features were already available in Turbo C++ for MS-DOS back in 1993, hence why I never liked C and only wrote straight C code when required to deliver projects in various contexts written in C.