Define and return a function from a function?

2020-04-21 04:20发布

问题:

How does one define and return a function inside a function?

For instance, we have a function like:

float foo(float val) {return val * val;}

Now, what is needed is a function like bar:

typedef float (*func_t)(float)
// Rubish pseudo code
func_t bar(float coeff) {return coeff * foo();}
// Real intention, create a function that returns a variant of foo
//  that is multiplied by coeff. h(x) = coeff * foo(x)

The only thing I've came up with so far is using lambda or a class. Is there a straight forward way to do this without being convoluted needlessly?

回答1:

Closures (with std::function) -using lambda functions- in C++11 are appropriate and recommended here. So have

std::function<int(int)> translate (int delta) { 
   return [delta](int x) {return x+delta;} }

then you might later code:

 auto t3 = translate(3);

Now t3 is the "function" which adds 3, later:

 int y = t3(2), z = t3(5);

and of course have y be 5 and z be 8.

You could also use some JIT compilation library to generate machine code on the fly, e.g. GCCJIT, or LLVM or libjit, or asmjit; or you could even generate some C++ (or C) code in some generated file /tmp/mygencod.cc and fork a compilation of that (e.g. g++ -Wall -O -fPIC /tmp/mygencod.cc -shared -o /tmp/mygencod.so) into a /tmp/mygencod.so plugin then dynamically load that plugin using dlopen on POSIX systems (and later dlsym to get a function pointer from a name; beware of name mangling for C++). I am doing such things in GCC MELT



回答2:

Use std::function

std::function<float(float)> bar(float coeff)
{
    auto f = [coeff](float x)
    {
        return coeff * foo(x);
    };

    return f;
}

You would then use it like this:

auto f = bar(coeff);
auto result = f(x);


标签: c++ function