Define and return a function from a function?

前端 未结 2 1666
死守一世寂寞
死守一世寂寞 2021-01-24 07:38

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;}
相关标签:
2条回答
  • 2021-01-24 08:26

    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

    0 讨论(0)
  • 2021-01-24 08:39

    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);
    
    0 讨论(0)
提交回复
热议问题