定义并返回一个函数的功能? [英] Define and return a function from a function?

查看:86
本文介绍了定义并返回一个函数的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,我们有一个函数,如:

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

现在需要的是像bar这样的函数:

$ $ $ $ $ $ $ $ typedef float(* func_t)(float)
//擦亮伪代码
func_t bar(float coeff){return coeff * foo();}
//真实意图,创建一个返回foo变体的函数
/ /乘以coeff。 h(x)= coeff * foo(x)

远在使用lambda或类。有没有一种简单的方法可以做到这一点,而不会毫无必要地变得复杂? 解决方案

闭包(使用 std :: function ) - 使用 lambda函数 - 在C ++ 11中是合适的,并在这里推荐。所以有

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

然后你可能会后来编码:

  auto t3 = translate(3); 

现在 t3 是函数后来增加3:

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

当然有 y 5并且 z 为8。



您也可以使用 JIT编译库,以实时生成机器码,例如 GCCJIT LLVM libjit asmjit ;或者你甚至可以在一些生成的文件 /tmp/mygencod.cc 中生成一些C ++(或C)代码,并为其编译(例如 g ++ -Wall -O -fPIC /tmp/mygencod.cc -shared -o /tmp/mygencod.so )转换为 /tmp/mygencod.so 插件然后动态加载该插件使用 dlopen 在POSIX系统上(以及后来的 dlsym 从名称中获取函数指针;注意名称对C ++进行修复)。我在 GCC MELT 中进行此类操作


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?

解决方案

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

这篇关于定义并返回一个函数的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆