Lambda as function parameter

后端 未结 2 1294
北海茫月
北海茫月 2020-12-12 15:09

What\'s the notation for declaring a lambda variable, or function parameter, without the use of auto or templates? Is there any way to do so? Or does the compil

相关标签:
2条回答
  • 2020-12-12 15:29

    You can use a polymorphic wrapper for a function object. For example:

    #include <functional>
    
    std::function<double (double, double)> f = [](double a, double b) { return a*b };
    
    0 讨论(0)
  • 2020-12-12 15:40

    Lambdas may hold state (like captured references from the surrounding context); if they don't, they can be stored in a function pointer. If they do, they have to be stored as a function object (because there is no where to keep state in a function pointer).

    // No state, can be a function pointer:
    int (*func_pointer) (int) = [](int a) { return a; };
    
    // One with state:
    int b = 3;
    std::function<int (int)> func_obj = [&](int a) { return a*b; };
    
    0 讨论(0)
提交回复
热议问题