mercredi 4 décembre 2019

In C++ Lambda Expressions, why would one prefer capturing by value over passing as arguments?

Presuming i would use Lamdba functions to define fuctions within functions to better structure the code, in what cases someone could prefer the second option over the first one, as the latter is clearly less reusable since no different arguements can be passed?

int main() {
    int foo = 1;
    int bar = 4;

    //Passing as Parameters
    auto add = [](auto a, auto b) {
        return a + b;
    };
    std::cout << "Add: " << add(foo, bar) << std::endl;

    //Capturing by value
    auto multiply = [=]() {
        return foo * bar;
    };
    std::cout << "Multiply: " << multiply() << std::endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire