mardi 6 juin 2023

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.

Aucun commentaire:

Enregistrer un commentaire