3 ms·
I would love for C++ to have more concise lambda syntax. Having to write [](int x, int y) { return x*y } even for the simplest lambda is a pain. Rust's syntax
by quirino 3y ago
I would love for C++ to have more concise lambda syntax.
Having to write
[](int x, int y) { return x*y }
even for the simplest lambda is a pain.
Rust's syntax looks ideal: |x, y| x*y. Haskell's is also sweet.
For my own purposes I've defined macros so that I can write L1(x+5) or L2(x*y) (the x and y are hardcoded in). Not elegant but it keeps me sane.
- ketzu 3y agoPersonally, I mostly want a more ergonomic way to write lambdas that I find more pleasant to type and read, even if it is as 'verbose'
- gpderetta 3y agoyou can get '_1 * _2' to work. Whether you want to is another story :D More seriously, even something like "(x,y) => x*y" would be nice. edit: I forgot that I managed to make the $(x, y)(x*y) syntax work a few years ago when trying to emulate constexpr lambdas: https://github.com/gpderetta/libtask/blob/master/lambda.cpp https://github.com/gpderetta/libtask/blob/master/lambda.cpp
- duped 3y agoPersonally I don't think closures need any additional syntax, just reuse function definition syntax and implicitly capture its context based on variable usage. I also hate the name "lambda" because it feels intentionally confusing and special. It's just a function that captures some context.
- nneonneo 3y agoBoost.Lambda (https://www.boost.org/doc/libs/1_62_0/doc/html/lambda.html https://www.boost.org/doc/libs/1_62_0/doc/html/lambda.html) is probably what you want, and even predates the introduction of proper lambdas into C++! Here’s a few simple examples cribbed from their documentation: // Set all elements to 1 for_each(a.begin(), a.end(), _1 = 1); // Print elements separated by spaces for_each(b.begin(), b.end(), std::cout << _1 << ' '); // Sort in reverse order sort(c.begin(), c.end(), *_1 > *_2);