【问题标题】:Is there a way to use Boost serialization on stl functional有没有办法在 stl 功能上使用 Boost 序列化
【发布时间】:2014-12-30 17:22:13
【问题描述】:

我有一个 stl 函数 std::function<int(int,int)> fcn_ 作为类的成员字段。有没有办法使用 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'

是否有一个头文件(比如&lt;boost/serialization/vector.hpp&gt;)我可以包含实现serializestd::function?或者有没有一种简单的方法可以自己实现?

谢谢!

【问题讨论】:

标签: c++11 serialization boost stl boost-serialization


【解决方案1】:

我还没有了解 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::functions 中(根据 http://en.cppreference.com/w/cpp/utility/functional/function/target),这将不起作用。

可以在coliru找到一个运行示例。

【讨论】:

  • 感谢您的回复,汤姆。但是我认为如果我将序列化写入文件并将其重新加载到不同的程序(或不同调用的同一程序)中,这将不起作用。正如这里所讨论的,可能没有办法在 C++ 中实现我的想法。请参阅此处的讨论 linklink
  • 有趣的链接,@YingXiong。可悲的是,这些答案已经被骗了,并且清楚地表明了您的问题应该如何被视为重复。当然,您可以提出跟进问题(“既然不能,如何使用语言核心功能对其进行序列化?”)
【解决方案2】:

您可能需要my_serializable_function&lt;int(int,int)&gt;,它知道如何从这样的描述符进行自我描述和重构。

换句话说:您自己编写代码

或者,您可能会查看一个脚本引擎,它已经包含类似的东西(Boost Python、几个 Lua 绑定、v8 引擎等)。虽然每个都有自己的权衡取舍,并且可能有点矫枉过正。

【讨论】:

    【解决方案3】:

    感谢 Tom and sehe 的回复。经过一番研究,我意识到我的想法在 C++ 中是不可能实现的——通常不可能序列化 std::function 对象。通过“序列化”,我的意思是能够将对象作为字节流从一个程序传输(读/写)到另一个程序,或者传输到同一个程序,但在同一台或不同的机器上进行不同的调用。下面的链接有更多关于这个话题的讨论:

    Serializing function objects

    Can std::function be serialized?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2021-09-03
      • 2012-08-12
      • 2019-12-14
      • 1970-01-01
      • 2012-02-23
      相关资源
      最近更新 更多