序列化C ++函子 [英] Serialize C++ functor

查看:68
本文介绍了序列化C ++函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以保存C ++ lambda / functor的函数体吗?

Can you save the function body of a C++ lambda/functor?

例如,说您拥有

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).

你能做到吗?

推荐答案

这个lambda没有状态(不是闭包),所以它是一个普通函数。

This lambda doesn't have state (not a closure), so it's an ordinary function.

因此,保存它与保存任何函数都是相同的问题。通常这是不可能的,但是只要您将其重新加载到完全相同的过程中,实际上就可以实现,只需通过 reinterpret_cast -设置函数指针到 char * 并读取足够数量的字节。但是,这将是高度不可移植的,并且可能在某些体系结构或某些编译器上根本无法使用。

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. This will be highly non-portable, though, and may not work at all on some architectures or with some compilers.

同样:没有符合标准的将代码视为数据的方式

另一方面,有些符号表达式库允许使用普通代码语法捕获表达式树,但随后您根本不需要处理函子(没有代码,只有数据)。

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).

这篇关于序列化C ++函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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