Does anyone really think lambda expressions help C++? I think it's nice to be able to create functors on the fly, although it's not always readable.
STL has <algorithm> which includes algorithms like std::for_each and std::find_if that accept functors/functions. In the past you usually had to create a functor to use these which was typically more code than just writing your own for loop. I thought lambdas would make functions like std::for_each practical. However, which is more readable?
int sum = 0;
std::vector<int> vArray = { 1, 2, 3, 4, 5 }; // Yes, you can do this in C++11
std::for_each(std::begin(vArray), std::end(vArray), [&sum](int x) {
sum += 2*x;
});
Or
int sum = 0;
std::vector<int> vArray = { 1, 2, 3, 4, 5 };
for (size_t i = 0; i < vArray.size(); ++i) {
sum += 2*vArray[i];
}
Better yet!
int sum = 0;
std::vector<int> vArray = { 1, 2, 3, 4, 5 };
for (int x : vArray) {
sum += 2*x;
}
I'm not seeing any elegant use of lambda expressions. Seeing functor definitions as parameters to other functions looks weird and messy. You could also just write a functor in an unnamed namespace to prevent namespace pollution. The functor could be named something intuitive like:
namespace {
struct NickEquals {
// ...
};
} // only valid in this translation unit
auto itr = std::find_if(std::begin(vUsers), std::end(vUsers), NickEquals("nslay")); // Find If Nick Equals "nslay" ... reads nicely!
Another one I have mixed feelings about is the auto type specifier. Yes, it is very convenient to write, but it's not very readable.
auto thing = Blah(); // So, what does Blah() return? Oh, right, best go look in the header. Oh, and did I mention 'auto' also consumes constness and pointers too (but not references)? Blah() might return a pointer ... or maybe a const. You'd never guess that by looking at it though.
// Oh yeah, If I changed Blah()'s return type, maybe it still compiles and runs when it shouldn't.
for (auto &x : vArray) {
// Wait, what is x again?
}
Anyone else have such thoughts?