I want to have an std::function that remembers its state. So I've tried this:
#include <iostream>
#include <functional>
class Dots {
public:
Dots(std::ostream & sink) : out_stream(sink) {}
std::function<void(const int n)> show = [this](int n) {
level+=n;
for (int i = 0; i < level; i++) out_stream << "*";
out_stream << "\n";
};
std::ostream & out_stream;
int level = 0;
};
int main() {
Dots d(std::cerr);
d.show(3);
d.show(1);
return 0;
}
This compiles with clang (Apple LLVM version 5.0) but it does not with gcc 4.7.3. The latter one says that: error: invalid use of non-static data member ‘Dots::level’. Can anyone explain me how to get it working?
My final goal is to make a generic method which I would use as a visitor. So in the real case I would have my
template
void traverse_depth_first(N root,A previsit_action,A invisit_action,A postvisit_action);
The type A is the the std::function object I'm trying to create. I thought lambdas will be good for this because they will allow easy creation of visiting methods in-place.
EDIT So I've applied the answer from Kerrek SB and the code above compiles both by gcc and clang. But it does not with icc 14.0.2, which complains that
error: "this" cannot be used inside the body of this lambda
Could anyone explain me why?