Function pointers working as closures in C++

前端 未结 4 1468
情书的邮戳
情书的邮戳 2021-01-19 13:53

Is there a way in C++ to effectively create a closure which will be a function pointer? I am using the Gnu Scientific Library and I have to create a gsl_function. This funct

4条回答
  •  没有蜡笔的小新
    2021-01-19 14:31

    Though bradgonesurfing has given a nice answer that will work for converting closures into gsl_functions without any further thought, I would like to share with you the idiom for doing a direct translation from C++ into C.

    Supposing you have the closure:

    double a;
    [&a](double x){return a+x;}
    

    You would convert translate this into an equivalent function pointer idiom as follows:

    struct paramsAPlusX{
        double* a;
        paramsAPlusX(double & a_):a(&a_){}
    }
    double funcAPlusX(double x, void* params){
       paramsAPlusX* p= (paramsAPlusX*)params;
       return *(p->a) + x;
    }
    
    //calling code:
    double a;
    paramsAPlusX params(a);
    gsl_function f;
    f.function=funcAPlusX;
    f.params=¶msAPlusX;
    //use f here.
    

    Many C libraries use this sort of idiom, and they don't all use a struct for it (they frequently pass it as two separate parameters to the function) so automatic conversion isn't always possible.

提交回复
热议问题