0

我正在尝试使用 boost::serialisation 来保存和加载一些对象。到目前为止,从 boost::tutorial 开始,我已经设法为所有不同的 stl 东西(向量、对、列表等)、派生类、boost 多数组和其他东西工作,但我一直在努力工作围绕如何序列化 boost::any 向量。让我提前说一下,我在论坛中找到并检查了一些关于 boost::varian 序列化的帖子,甚至还有一个关于 boost::any 的帖子(甚至有一个几乎相同的标题),但我还是没能解决我的问题. 所以让我举一个小例子:

说我有这门课:

 class class_2
 {
   private:

     template<class Archive>
     void serialize(Archive & ar, const unsigned int version)
      {
         ar & degrees;
         ar & minutes;
         ar & seconds;

      for( std::vector<boost::any>::iterator it = v_any.begin() ; it != v_any.end() ; ++it  ) {
        //Trying to cast all the possible types that may enter the 
        //boost any vector, for the sake of this example let's just 
        //say that we will only pass a second class called name class_1
        //to the boost::any vector and we only have to cast this class
        if (it->type() == typeid(class_1)){
            class_1 lan = boost::any_cast< class_1 > (*it );
                ar &  (lan);
        }

       }// for boost::any*/
   } //serialization
   public:
      int degrees;
      int minutes;
     float seconds;


     class_2(){};
     class_2(int d, int m, float s) :
       degrees(d), minutes(m), seconds(s)
         {}

   std::vector<boost::any> v_any;
 };

更准确地说,我们期望这个小示例存在于 boost::any 向量中的 class_1 是以下类:

 class class_1
 {
    private:
    friend class boost::serialization::access;
     template<class Archive>
     void serialize(Archive & ar, const unsigned int version)
     {
        ar & a;
     }

     public:
     class_1(){};
     int a;
    };

因此,当我使用 main 函数编译上述代码时,我在其中保存并加载了一个包含 boost::any 向量的 class_2 对象,一个 class_1 的对象,一切都会编译甚至运行:

int main() {

class_1 alpha;
class_2 beta;

alpha.a=5;
beta.v_any.push_back(alpha);

    std::ofstream ofs("file");
// save data to archive
{
    boost::archive::text_oarchive oa(ofs);
    // write class instance to archive
    oa << beta;
    // archive and stream closed when destructors are called
}

// ... some time later restore the class instance to its orginal state
class_2 newclass;
{
    // create and open an archive for input
    std::ifstream ifs("file");
    boost::archive::text_iarchive ia(ifs);
    // read class state from archive
    ia >> newclass;
    // archive and stream closed when destructors are called
}

return 0;
}

再次加载的 newclass 对象有一个空的 boost::any 向量,其中没有保存任何内容。所以我的问题是我在上面的代码中做错了什么,我应该改变什么才能正确序列化 boost::any 向量..?任何帮助/建议将不胜感激。

4

0 回答 0