简体   繁体   English

序列化C ++函子

[英]Serialize C++ functor

Can you save the function body of a C++ lambda/functor? 您可以保存C ++ lambda / functor的函数体吗?

For example, say you have 例如,说你有

light0->lightFunction = []( real tEl, real pAz ) -> Vector {

  return Vector(
    // red is up lobe
    std::max<real>( 0., 5*cos(tEl)-4 ),

    // green lower lobe
    std::max<real>( 0., -4*sin(tEl-PI)*cos(pAz-2.5)-3),

    0. ) ;
} ;

And you want to save the function body, so you can load it later (instead of always having to hard code it). 并且您想要保存函数主体,以便以后可以加载它(而不是总是必须对其进行硬编码)。

Can you do it? 你能做到吗?

This lambda doesn't have state (not a closure), so it's an ordinary function. 这个lambda没有状态(不是闭包),因此它是一个普通函数。

Saving it therefore is the same problem as saving any function. 因此,保存它与保存任何功能是相同的问题。 It's not possible in general, but as long as you're loading it back into the exact same process, it may be possible in practice, just by reinterpret_cast -ing the function pointer to a char* and reading a sufficient number of bytes. 通常这是不可能的,但是只要您将其重新加载到完全相同的进程中,实际上就可以实现,只需reinterpret_cast将函数指针指向char*并读取足够数量的字节即可。 This will be highly non-portable, though, and may not work at all on some architectures or with some compilers. 但是,这将是高度不可移植的,并且在某些体系结构或某些编译器上可能根本不起作用。

Again: There is no standard-compliant way to treat code as data . 再次: 没有将代码视为data的符合标准的方法

On the other hand, there are symbolic expression libraries that allow capture of an expression tree using ordinary code syntax, but then you're not dealing with a functor at all (there is no code, only data). 另一方面,有些符号表达式库允许使用普通代码语法捕获表达式树,但是您根本不需要处理函子(没有代码,只有数据)。

To add to Ben's answer, I'm now doing this: 为了增加Ben的答案,我现在正在这样做:

vector< function <Vector ( real tEl, real pAz )> > funcs ;
funcs.resize( 5 ) ;
// write functions here
funcs[ 0 ] = []( real tEl, real pAz ) -> Vector {
  return Vector(
    // red is up lobe
    std::max<real>( 0., 5*cos(tEl)-4 ),

    // green lower lobe
    std::max<real>( 0., -4*sin(tEl-PI)*cos(pAz-2.5)-3),

    0. ) ;

funcs[ 1 ] = ...

Then when saving, I only save an integer, and at load, point the integer to the correct function in the source code file. 然后在保存时,我只保存一个整数,并在加载时将整数指向源代码文件中的正确函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM