7 ms·
The Evolutions of Lambdas in C++14, C++17 and C++20
- kello 5y agoI had a friend show me some of the stuff you can do in C++ nowadays. I had no idea C++ had evolved so much!
- samsaga2 5y agoIs there any flag in some c++ compiler that forces to you to use the newer features? For example, forbidding non-auto declarations.
- cjfd 5y agoQuite apart from not being possible forbidding non-auto declarations also sounds like a terrible idea. I am not really that fond of the auto keyword. In some cases it is necessary and/or helpful but it is also very helpful to be able to tell what the type of a variable is at a glance. I think the auto keyword should be used sparingly.
- criddell 5y agoNo.
- MauranKilom 5y agoThere is tooling along those lines. I wouldn't expect to find a tool that forbids non-auto declarations, but there are certainly some that suggest when something could've been auto.
- MontagFTB 5y agoRight. clang-tidy lets you specify rules you’d like it to enforce in the code you pass through it. It’s not a part of the compilation process, but uses the same underlying driver (if you’re building with clang)
- pjmlp 5y agoOn large projects it can be integrated into the build pipeline, so in a sense it becomes part of the product compilation process, even if not on the local workstation. I am a big friend to push good coding practices into the CI/CD configuration, regardless of the programming language. Anyone can do whatever they feel like on their own computer, but the overall product has guidelines to follow, specially relevant in projects that live from changing consulting companies all the time.
- bluescarni 5y agoAnother new lambda feature in C++20 is default constructability. I am surprised this is not mentioned in the article.
- vitus 5y ago> Even if you don’t need to handle several types, this can be useful to avoid repetition and make the code more compact and readable. ... > namespace1::namespace2::namespace3::ACertainTypeOfWidget Deeply nested namespaces are problematic in themselves due to namespace resolution (e.g. see https://abseil.io/tips/130 https://abseil.io/tips/130), but templates should never be an answer to "my type is too long to type out". You're hurting yourself at compile-time, and your code is now more error-prone as you can pass in any argument. Just add a using-decl (or a namespace alias if the base name isn't meaningful enough for you).
- cjfd 5y agoYes, deeply nested namespaces are not nice. I think boost really dropped the ball on this. boost::asio::ip::tcp should have been boost::tcp. Are they trying to be as bad as java?
- tialaramex 5y agoAs the article explains it's not "as bad as Java" it's worse, what Java does actually makes sense in Java, maybe you have to type slightly more characters but Java is already a verbose language best suited to heavy tool-assist. However it doesn't make sense in C++ because the benefits Java gets don't apply and the price is heavier. There are a bunch of things like this in C++ where superficially C++ feature X is like feature Y in another language, and so C++ programmers wrongly assume the problems with feature X must also plague feature Y. I'm sure the reverse happens too.
- jlarocco 5y ago> There are a bunch of things like this in C++ where superficially C++ feature X is like feature Y in another language, and so C++ programmers wrongly assume the problems with feature X must also plague feature Y. I'm sure the reverse happens too. Yes! I've noticed this also. Several recent C++ changes are copying idioms from other languages, and sometimes the standards committee seems to have missed the point or misunderstood how the features are used in the language they're copying. The results are superficially similar, but not quite what I'd expect after knowing the feature from the source language.
- b20000 5y agoi was in a leetcode BS interview a while ago with a googler who thought i could not write code in c++ because i could not remember lambda syntax. i only use maybe 30% of c++ features in my software and have been doing this for over 20 years. it’s only recently i started using lambdas more, but still stay away from them because of the potential hidden allocations.
- steerablesafe 5y agoWhat kind of hidden allocations?
- huhtenberg 5y agoThat are used to hold captured variables and values. Internally, lambdas are function pointers + the context, and the context may or may not be dynamically allocated depending on how lambdas are used.
- bstamour 5y agoInternally, lambdas are structs with the "function call" operator overload. Context is done via members of the struct: capture by-value, and the struct copies them and stores its own, capture by reference, and the struct member is a reference. There should be zero heap allocation in any case.
- huhtenberg 5y agoYou capture by value a variable that allocates and you get a heap allocation.
- kllrnohj 5y agoThat's dependent on the captured type's copy (or move) behavior, and is completely different from your claim that how the lambda is used can influence this. Lambdas themselves never heap allocate.
- 1024core 5y agoGeneralised capture In C++11, lambdas can only capture existing objects in their scope: int z = 42; auto myLambda = [z](int x){ std::cout << x << '-' << z + 2 << '\n'; }; ... But with the powerful generalised lambda capture, we can initialise captured values with about anything. int z = 42; auto myLambda = [y = z + 2](int x){ std::cout << x << '-' << y << '\n'; }; Am I the only one who doesn't see much of a difference here?
- ynik 5y agoGeneralized capture is primarily useful for move semantics: std::function<int()> make_func(std::unique_ptr<int> ptr) { return [p = std::move(ptr)]() { return *p; } } Without generalized capture syntax, there's no good way to transfer ownership into the closure (a regular `[ptr]` capture would attempt to make a copy, and a by-ref `[&ptr]` capture would lead to a use-after-free).
- deleted 5y ago[deleted]
- stabbles 5y agoC++23 drop the word auto? myLambda = [](&&x){ std::cout << x << '\n'; }; what's the point of having to write auto everywhere
- bruce343434 5y agosyntactical disambiguation, there's already something called "the most vexing parse". C++ is full of little holes like these and getting rid of auto would surely at least double compile times or at worst make parsing C++ actually impossible.
- gsliepen 5y agoYes, those things creep up in various places. Some are fixed, like when you have std::vector<std::vector<int>> where it used to give an error because it thought >> was an operator. But recently I discovered this one: int x[100] = {}; // just a regular array int val = x[[]{return 42;}()]; // compile error! Once again, greedy parsing is the culprit; here it thinks [[ is the start of an attribute.
- klyrs 5y agoOn one hand, nice catch... on the other hand... why do you want to do that??
- pjmlp 5y agoThat is what happens when a language makes the compromise to be copy-paste compatible with https://cdecl.org/ https://cdecl.org/
- ncmncm 5y agoMore to the point, it means the language continues to interpret header files from C libraries the same way that the C compiler always has.
- 5y ago
- mgaunard 5y agoTemplate lambdas is in my opinion the most useful evolution and has been a long time coming. I figure it was held back by template haters who want terse syntax and don't understand how it's much more powerful than auto/concepts. I wouldn't say it's a smaller evolution than previous iterations.
- ncmncm 5y agoAgreed. C++11 was a major evolutionary step for the language, but C++14 made it fun, too. C++20 is as large a step as C++11, but it will take as long for people to absorb. C++23 will bring usability improvements for async/await and maturity to library ranges.
- gpderetta 5y agoRegarding returning lambdas, of course it could be done even in c++11 via std::function.
- steerablesafe 5y agoThat is not really the same. `std::function` is a heavy-weight type-erased wrapper over callable types.
- nickysielicki 5y agoUnfortunately it’s the only way to get a recursive lambda, as far as I’m aware.
- gpderetta 5y agoYou can use a fix point combinator.
- mhogomchungu 5y agoProblems with std::function:- 1. It can not hold move only callable objects. 2. It heap allocate stored callable object if the object is large enough.
- stargrazer 5y agoCan you point to better alternate ways or idioms?
- MontagFTB 5y agostlab has a task type that works around a couple of these issues: https://stlab.cc/libraries/concurrency/task/task/ https://stlab.cc/libraries/concurrency/task/task/
- MauranKilom 5y agoIt's possible to write something like `std::unique_function` (which uniquely owns the stored callable and can be moved but not copied). That's often preferable for storing functors. Example: https://github.com/facebook/folly/blob/main/folly/docs/Function.md https://github.com/facebook/folly/blob/main/folly/docs/Funct...