试图使用Boost :: any的boost :: serialization

时间:2016-05-17 13:48:55

标签: c++ serialization boost vector boost-any

我正在尝试使用boost :: serialization来保存和加载一些对象。 从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 ::任何没有保存的向量。 所以我的问题是我在上面的代码中做错了什么,为了正确序列化boost :: any向量,我应该改变什么? 任何帮助/建议都将非常感激。

0 个答案:

没有答案