In C++11, how do you declare a function that takes a lambda expression as an argument? I can find plenty of resources online for declaring lambdas or taking them as template parameters, but what I'd really like to do is be able to make use of lambdas as easy-to-declare callback handlers, similar to what's made possible by closures in JavaScript and code blocks in Objective-C.
Essentially, the classic C++ construct I want to replace with a lambda is something like:
class MyCallback {
public:
virtual ~MyCallback() {}
virtual void operator(int arg) = 0;
};
void registerCallback(const std::shared_ptr<MyCallback> &);
void foo(void) {
int a, b, c;
class LocalCallback: public MyCallback {
int a, b, c;
public:
LocalCallback(int a, int b, int c): a(a), b(b), c(c) {}
void operator(int arg) { std::cout << (a+b+c)*arg << std::endl; }
};
registerCallback(std::shared_ptr<MyCallback>(new LocalCallback(a,b,c)));
}
which would be simplified into:
void registerCallback(/* WHAT GOES HERE? */);
void foo(void) {
int a, b, c;
registerCallback([=](int arg){std::cout << (a+b+c)*arg << std::endl; })
}
So, what goes where I have written /* WHAT GOES HERE? */
?
EDIT: This is for the purpose of storing a callback to be called back later, rather than for it being immediately consumed and called.
function
argument and the caller can use (or not) a lambda as they like.