C++ lambdas
2016-11-30 12:42I was catching up on C++11 last night. Learned about lambdas, and started playing around with them. A neat addition. But did they provide full closure capability, like creating a snapshot of state that the function can privately modify? Looked like no, and I was all set to be disappointed.
But at a job interview yesterday, I learned about the mutable keyword, which was described as letting you modify const things, like deep in a const object hierarchy. "Why would you even do that?" was my first reaction, though I can vaguely imagine why, "for the same reason that Haskell's purity annoyed me."
So I remembered that, and figured I would try adding mutable to the lambda. Ka-ching!
Output:
1
3
6
10
15
21
28
36
45
55
0
Not that you need the external sum here, you could drop it and have [sum=0] for the lambda, but it illustrates the idea. Which isn't obscure, I saw it in the docs I was reading shortly after returning to them, but still, I found this on my own.
I've been applying to a bunch of C++ jobs more because of experience than because of any deep love for the language, but features like this and auto (type inference) and others from C++11/14 make it a lot more appealing.
But at a job interview yesterday, I learned about the mutable keyword, which was described as letting you modify const things, like deep in a const object hierarchy. "Why would you even do that?" was my first reaction, though I can vaguely imagine why, "for the same reason that Haskell's purity annoyed me."
So I remembered that, and figured I would try adding mutable to the lambda. Ka-ching!
#include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vectorv; for (int i=1; i<=10; i++) { v.push_back(i); } int sum=0; for_each(begin(v), end(v), [sum](int n) mutable {sum+=n; cout << sum << endl;}); cout << sum << endl; }
Output:
1
3
6
10
15
21
28
36
45
55
0
Not that you need the external sum here, you could drop it and have [sum=0] for the lambda, but it illustrates the idea. Which isn't obscure, I saw it in the docs I was reading shortly after returning to them, but still, I found this on my own.
I've been applying to a bunch of C++ jobs more because of experience than because of any deep love for the language, but features like this and auto (type inference) and others from C++11/14 make it a lot more appealing.