C function pointers with C++11 lambdas

后端 未结 5 1143
自闭症患者
自闭症患者 2020-11-30 10:55

So i\'m trying to write an Integration function to be used with c++11 lambdas. The code looks something like this:

double Integrate(std::function

        
5条回答
  •  醉梦人生
    2020-11-30 11:11

    A std::function<> cannot be converted to a function pointer. std::function<> are function objects that can potentially hold state while regular functions are stateless (kind of, you could potentially have static variables, but that is a different thing).

    On the other hand, stateless lambdas can be converted to a function pointer, so you could potentially change the signature of your function to take a function pointer directly and the lambda will be converted:

    double Integrate(double(*func)(double,void*), double a, double b, 
                     std::vector & params) // !!!
    
    std::vector p{2,3};
    Integrate([](double a,void* param)
       {
          std::vector *p = static_cast*>param;
          return p->at(0)*a+p->at(1);
       }
       ,0,3,p);
    

    Note that it is illegal to bind an rvalue to a non-const reference, so you cannot legally pass {2,3} as the last argument to Integrate (even if Visual Studio allows you to), you will need to create a named variable.

提交回复
热议问题