Define and return a function from a function?

How to define and return a function inside a function?

For example, we have a function such as:

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

Now we need 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 came up with is to use a lambda or class. Is there a direct way to do this without undue perversion?

+1
source share
2 answers

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

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

then you can further code:

  auto t3 = translate(3); 

Now t3 is a β€œfunction” that adds 3, later:

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

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

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

+3
source

Use std :: function

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

Then you will use it as follows:

 auto f = bar(coeff); auto result = f(x); 
+5
source

Source: https://habr.com/ru/post/1239332/


All Articles