C++ lambda with captures as a function pointer

后端 未结 8 887
离开以前
离开以前 2020-11-22 15:35

I was playing with C++ lambdas and their implicit conversion to function pointers. My starting example was using them as callback for the ftw function. This works as expecte

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 15:44

    My solution, just use a function pointer to refer to a static lambda.

    typedef int (* MYPROC)(int);
    
    void fun(MYPROC m)
    {
        cout << m(100) << endl;
    }
    
    template
    void fun2(T f)
    {
        cout << f(100) << endl;
    }
    
    void useLambdaAsFunPtr()
    {
        int p = 7;
        auto f = [p](int a)->int {return a * p; };
    
        //fun(f);//error
        fun2(f);
    }
    
    void useLambdaAsFunPtr2()
    {
        int p = 7;
        static auto f = [p](int a)->int {return a * p; };
        MYPROC ff = [](int i)->int { return f(i); };
        //here, it works!
        fun(ff);
    }
    
    void test()
    {
        useLambdaAsFunPtr2();
    }
    

提交回复
热议问题