序列化 C++函子
你能保存 C++ lambda/函子的函数体吗?
例如,假设您有
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. ) ;
} ;
并且想要保存函数体,以便稍后可以加载它(而不是总是必须对其进行硬编码)。
你能做到吗?
Can you save the function body of a 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个 lambda 没有状态(不是闭包),所以它是一个普通的函数。
因此,保存它与保存任何函数都是同样的问题。一般来说这是不可能的,但只要您将其加载回完全相同的进程,在实践中就有可能,只需将函数指针重新转换为 char * 并读取足够数量的字节。不过,这将是高度不可移植的,并且可能在某些体系结构或某些编译器上根本不起作用。
再次强调:没有符合标准的方法将代码视为数据。
另一方面,有一些符号表达式库允许使用普通代码语法捕获表达式树,但是您根本不处理函子(没有代码,只有数据)。
This lambda doesn't have state (not a closure), so it's an ordinary function.
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 achar*
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.Again: There is no standard-compliant way to treat code as 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).
为了补充 Ben 的答案,我现在这样做:
然后在保存时,我只保存一个整数,并在加载时将整数指向源代码文件中的正确函数。
To add to Ben's answer, I'm now doing this:
Then when saving, I only save an integer, and at load, point the integer to the correct function in the source code file.