lundi 22 juillet 2019

C++11 define lambda function in private

I want to hide details of the lambda function into C++ class' private part.

I tried to separate the lambda function part from for_each() function.

class Sol{
private:
    vector<int> vec = vector<int>{1,2,3,4,5};
    int target = 10;
    auto lambdaFunc = [=](int& v) { v += target; };

public:
    void addConst() {
        for_each(vec.begin(), vec.end(), lambdaFunc);
    }

    void printVec() {
        for_each(vec.begin(), vec.end(), [](int v){cout << v << endl;});
    }
};

int main() {
    Sol sol;
    sol.addConst();
    sol.printVec();

    return 0;
}

If I don't separate lambdaFunc from the for_each() function, I got elements of vector printed out. However, by separating lambdaFunc, I got error message:

error: non-static data member declared 'auto'

Changing auto to static auto didn't solve.

Aucun commentaire:

Enregistrer un commentaire