Passing capturing lambda as function pointer

前端 未结 9 2233
-上瘾入骨i
-上瘾入骨i 2020-11-21 06:58

Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.

Consider the follo

9条回答
  •  误落风尘
    2020-11-21 07:43

    A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section 5.1.2 [expr.prim.lambda] says (emphasis mine):

    The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

    Note, cppreference also covers this in their section on Lambda functions.

    So the following alternatives would work:

    typedef bool(*DecisionFn)(int);
    
    Decide greaterThanThree{ []( int x ){ return x > 3; } };
    

    and so would this:

    typedef bool(*DecisionFn)();
    
    Decide greaterThanThree{ [](){ return true ; } };
    

    and as 5gon12eder points out, you can also use std::function, but note that std::function is heavy weight, so it is not a cost-less trade-off.

提交回复
热议问题