2014-11-03 78 views
0

我有一个stl函数std::function<int(int,int)> fcn_作为类的成员字段。有没有一种方法使用boost序列化来序列化它?如果我做了以下有没有办法使用stl函数上的Boost序列化

template<class Archive> 
    void serialize(Archive &ar, const unsigned int version) { 
    ar & fcn_; 
    } 

我得到了错误

/opt/local/include/boost/serialization/access.hpp:118:9: error: 'class std::function<int(int, int)>' has no member named 'serialize' 

是否有一个头文件(这样说<boost/serialization/vector.hpp>)我可以包括实现serializestd::function?还是有一个简单的方法来实现自己?

谢谢!

+0

可能重复(http://stackoverflow.com/questions/18173339/can -stdfunction-be-serialized) – 2014-11-17 13:29:42

回答

0

感谢汤姆和谢赫的回应。经过一番研究之后,我意识到我所想的在C++中是不可能的 - 通常不可能序列化一个std::function对象。通过“序列化”,我的意思是能够将对象作为字节流从一个程序传输(读取/写入)到另一个程序,或者传输到相同或不同计算机上的相同程序。下面的链接有更多关于这个主题的更多讨论:[?功能可标准::被序列化]

Serializing function objects

Can std::function be serialized?

0

我还没有看看Boost序列化如何工作,但这里有一个可能的方法。

template<typename T> 
std::ostream& serialize(std::ostream& out, const std::function<T>& fn) 
{ 
    using decay_t = typename std::decay<T>::type; 
    if(fn.target_type() != typeid(decay_t)) throw std::runtime_error(std::string(typeid(decay_t).name()) + " != " + fn.target_type().name()); 
    const auto ptr = fn.template target<decay_t>(); 
    out << reinterpret_cast<void*>(*ptr); 
    return out; 
} 

template<typename T> 
std::istream& deserialize(std::istream& in, std::function<T>& fn) 
{ 
    using decay_t = typename std::decay<T>::type; 
    void* ptr = nullptr; 
    in >> ptr; 
    fn = reinterpret_cast<decay_t>(ptr); 
    return in; 
} 

请注意,如果你存储的lambda表达式或函数对象在std::function S(按http://en.cppreference.com/w/cpp/utility/functional/function/target),这是不行的。

可以找到一个运行示例coliru

+0

谢谢你的回复,汤姆。但是,如果我将序列化写入文件并将其重新加载到不同的程序中(或者在不同的调用中使用相同的程序),我认为这不会起作用。正如我们在这里讨论的那样,在C++中可能没有办法做到我想到的。请参阅这里的讨论[链接](http://stackoverflow.com/questions/12338265/serializing-function-objects)和[链接](http://stackoverflow.com/questions/18173339/can-stdfunction-be-serialized ) – 2014-11-04 02:14:24

+0

有趣的链接@YingXiong。可悲的是,这些答案已经是愚蠢的,并且清楚地表明你的问题应该被认为是重复的。当然,你可以问_关注问题(“如何使用语言核心功能序列化它,因为你无法使用语言核心功能?”) – sehe 2014-11-04 07:20:39

0

您可能需要my_serializable_function<int(int,int)>,它知道如何从这样的描述符中自我描述和重构。

换句话说:你自己自己写代码。另外,你可能会看一个脚本引擎,它已经包含这样的东西(Boost Python,几个Lua绑定,V8引擎等)。虽然每个都有自己的一套权衡,并可能是矫枉过正。

相关问题