11

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.

4
  • Using local types as template arguments isn't legal in C++03. Some compilers allow it as an extension though.
    – bames53
    May 23, 2012 at 20:19
  • 2
    The advantage of a lambda is that it makes writing callbacks easier. You don't specifically write code that will be used with lambdas, you just write code that will take a function argument and the caller can use (or not) a lambda as they like. May 23, 2012 at 20:19
  • @barnes53 The code I posted doesn't use local types as a template argument. MyCallback is a global, and the local type is being wrapped in std::shared_ptr<MyCallback>. I use this pattern at work all the time, which is why I'm interested in the way C++11 makes it better. :)
    – fluffy
    May 23, 2012 at 20:26
  • @MahmoudAl-Qudsi yes, which is exactly why I was asking this question!
    – fluffy
    May 23, 2012 at 20:27

3 Answers 3

19

Usually const std::function<void(int)> & or std::function<void(int)>.

I'm not sure what the verdict is on whether std::function should be passed by const reference or by value. Probably by value is fine, especially since you're going to copy it anyway to store.

In case it isn't clear in the middle of all that syntax, void(int) is a function type, and std::function<T> means approximately, "a functor with the same signature as functions of type T".

Lambdas themselves have anonymous types. There is no way to name the type of your lambda expression, and the types of different lambda expressions with the same signature are different:

auto foo = [=](int arg){std::cout << (a+b+c)*arg << std::endl; };
auto bar = [=](int arg){std::cout << (a+b+c)*arg << std::endl; };
// foo and bar have different types, accessible as decltype(foo), decltype(bar)

Hence the need for std::function, which basically is a type-erasing wrapper to gather together different functors with the same signature into a common type. It's the bridge between static polymorphism with templates, and the dynamic polymorphism you need if you want to register a callback, store it for later, and then call it without having "remembered" the original type.

1
  • Thanks. As is typical, I came across std::function about 30 seconds after posting my question, but your answer is way better than what I'd have written. Also accepting it for the decltype() stuff and the fuller explanation of how lambdas and function-types work in C++11. (Or, I will accept it when SO lets me...)
    – fluffy
    May 23, 2012 at 20:24
7
void registerCallback(const std::function<void(int)>& callback);
5

Consider using a function template. There are a variety of good reasons to, such as better behaviour when overloading (overloading on std::function is painful):

template<typename Functor>
void registerCallback(Functor&& functor);

(You can also accept the parameter as Functor functor, that's not too important.)

If the code needs to e.g. store the functor later on, then that will likely be held inside an std::function. Where you want to avoid std::function is in function parameters.

14
  • Wouldn't this require that the implementation be kept visible to anything that makes use of it (i.e. in the header file)? Or is C++11 finally able to keep templatized methods' implementation details hidden?
    – fluffy
    May 23, 2012 at 22:02
  • @fluffy : Yes, that requirement holds true. But does that really matter?
    – ildjarn
    May 23, 2012 at 23:46
  • @ildjarn It does if I don't want to expose the implementation in a public header file, or if I want this to be a virtual method on an interface, not to mention all the other edge conditions with shared libraries and other situations where templatized methods just plain don't work.
    – fluffy
    May 24, 2012 at 0:21
  • 1
    @fluffy You missed the point of having a function template (with again a minimal body to avoid any objection with the visible implementation). By the way the problem with std::function is that it's too lax.
    – Luc Danton
    May 24, 2012 at 6:24
  • 1
    I wrote the answer short (and am still considering keeping it that way) because the question is short. I could write more about the proper use of std::function and functors but I have no way to know if that's relevant for your purposes given the code you posted (not that I need more -- all of this is fine to me). I can only give you a very generic and general guideline to a non-specific question. It's true that I've been wondering if we do need in fact a "When not to use std::function" FAQ to link to such questions.
    – Luc Danton
    May 24, 2012 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.