I REALLY love lambdas and having the ability to use them in C++ is a pleasure. But, as I’m used to Haskell, where lambdas fit really well into the syntax, I’m struggling with how to use them in C++ without writing unreadable cluttered long code lines.
So, as an example, suppose I’d write this:
vector<double> foo(10,0.2);
for_each(foo.begin(), foo.end(), [](double x){ std::cout << x << " ";})
this is not so difficult to read, the lambda expression is pretty small. But if I have a two or three line long function inside that for_each, this could become a problem for my
code-reading-skills:
vector<double> foo(10,0.2);
randomNumberGenerator bar;
for_each(foo.begin(), foo.end(), [](double x){ std::cout << "hello!"; x+=bar()/(1+bar()); std::cout << x << " ";})
//sorry, I couldn't think of a less stupid example...
This line is starting to get annoyingly long and difficult to read for my taste…
What is your preferred code conventions for this case? Should I write:
for_each(foo.begin(), foo.end(),
[] (double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
or something like it? I still think this syntax feels a bit unnatural and difficult to read… 🙁
I usually go for
I’ve written some several hundred line lambdas.