Search code examples
c++c++11lambda

How to use lambda functions in C++11?


I have an object that needs a function passed to it in order to work. Something like

int doSomething(string a, int b, string(*lookUpFunction)(string a, int b)) {
    return lookUpFunction(a,b).length():
}

This is simplified to just include needed parameters and correct return types. I believe I have defined this correctly but please correct me if I am wrong. lookUpFunction takes a string and an int and returns a string.

Where my problem comes in is using this function. I would think I would use like this

class x {
    DataBase* db;
public:
    int myFunc();
}


int x::myFunc() {
    return doSomething("a",1,[this](string a, int b)->string {
        return db->someFuncThatTakesStringAndInt(a,b);
    });
}

But my IDE throws errors. If I remove "this" it says db isn't accessible. With it in it says the lambda function is not castable to correct format.


Solution

  • Your doSomething() function is taking in a plain C-style function pointer for its lookUpFunction callback.

    However, a capturing lambda is not convertible to a function pointer, only a non-capturing lambda is convertible. You are capturing this, which is why you can't pass in your lambda as shown.

    Instead of a function pointer, your doSomething() function will need to take in a callback object as either a std::function or a template parameter, eg:

    int doSomething(string a, int b, std::function<string(string, int)> lookUpFunction) {
        return lookUpFunction(a,b).length():
    }
    
    template<typename Callable>
    int doSomething(string a, int b, Callable lookUpFunction) {
        return lookUpFunction(a,b).length():
    }
    

    Now, you can pass your capturing lambda to either one.