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;}
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
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);