C++11 Lambda functions implicit conversion to bool vs. std::function

前端 未结 4 732
时光取名叫无心
时光取名叫无心 2021-01-12 05:36

Consider this simple example code:

#include 
#include 

void f(bool _switch) {
    std::cout << \"Nothing really\" &l         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 06:12

    A lambda function with no capture can be converted to a regular function pointer, which then has a standard conversion to a bool.

    If you take the std::function by non-const reference, then that eliminates it as a candidate, since converting the lambda to a std::function requires a temporary, and a temporary cannot bind to a non-const reference. That just leaves f(bool) as a candidate, so there is no ambiguity.

    There are many ways you could avoid the ambiguity. For example, you could create a std::function variable first:

    std::function g = [](int _idx){ return 7.9;};
    f(g);
    

    or you could cast the lambda:

    f(std::function([](int _idx){return 7.9;}));
    

    You could have a helper function:

    template
    std::function make_function(T *f) { return {f}; } 
    
    int main ( int argc, char* argv[] ) {
        f(make_function([](int _idx){ return 7.9;}));
        return 0;
    }  
    

    or you could grab the particular function you are interested in:

    int main ( int argc, char* argv[] ) {
        void (*f_func)(std::function) = f;
        f_func([](int _idx){ return 7.9;});
        return 0;
    }
    

提交回复
热议问题