Conversion error in a method that returns a lambda expression

92 Views Asked by At

This code works without problem:

#include "iostream"
#include  "functional"
std::function<double (double)> retFun(double* a) {
     return [a](double x) { return x+*a; };
 }

 int main(){

 double*e = new double(3);
 std::cout << retFun(e)(3) << std::endl;}

but if I declare retFun in an object:

.h

class InternalVariables : public Page
{
private:
    std::function<double ()> retFun(double* a);
};

.cpp

std::function<double ()> InternalVariables::retFun(double *a)
{
    return [a](double b){ return b+ *a;};
}

I obtain the following error

error: could not convert ‘InternalVariables::retFun(double*)::__lambda44{a}’ from ‘InternalVariables::retFun(double*)::__lambda44’ to ‘std::function’ return [a](double b){ return b+ *a;};

1

There are 1 best solutions below

0
On BEST ANSWER

std::function<double ()> means that your wrapped function object will take no arguments and return a double. [a](double b){ return b+ *a;} is a lambda that takes a double and returns a double. The two signatures are mismatched.

You should change your return type to std::function<double (double)>.


Also:

  • Standard Library headers should be included with <...>. Example: <iostream>.

  • There's no need to allocate a double on the heap to get a pointer to it. Just use & on a double on the stack. Allocations in C++11 should be always done through smart pointers, do not use new/delete.

  • You might want to simply return auto instead of std::function. The latter is a type-erased wrapper over any function object. Lambdas have their own anonymous type.