Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

serialization - Serialize C++ functor

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...