首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用Cereal序列化std::vector

无法使用Cereal序列化std::vector
EN

Stack Overflow用户
提问于 2017-10-27 09:48:13
回答 1查看 2.7K关注 0票数 2

我是序列化新手,在使用Cereal library序列化std::vector对象时遇到了问题。下面是一个示例,说明了这个问题:

代码语言:javascript
复制
class MyClass
{
    int x, y, z;

    class MyOtherClass
    {
        string name, description;

    public:

        template<class Archive>
        void serialize(Archive & archive)
        {
            archive(name, description);
        }
    };

    vector<MyOtherClass> Victor;
    vector<int> ints;

public: 

    template<class Archive>
    void serialize(Archive & archive)
    {
        archive(x, y, z, ints); // error C2338: cereal could not find any output serialization functions for the provided type and archive combination.
    }
};

尝试序列化ints对象或Victor对象都会导致error C2338: cereal could not find any output serialization functions for the provided type and archive combination.

下面是我在main函数中使用的代码:

代码语言:javascript
复制
MyClass MyObject;
ofstream datafile(path, ios::binary);
{ cereal::BinaryOutputArchive oarchive(datafile); oarchive(MyObject); }

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-12-20 07:07:12

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp> 
// See details in http://uscilab.github.io/cereal/stl_support.html

class MyClass {
  int x, y, z;

  class MyOtherClass {
    string name, description;

  public:
    template <class Archive>
    void serialize( Archive &archive )
    {
      archive( CEREAL_NVP( name ), CEREAL_NVP( description ) );
    }
  };

  vector<MyOtherClass> Vector;
  vector<int>          ints;

public:
  template <class Archive>
  void serialize( Archive &archive )
  {
    archive( CEREAL_NVP( x ), CEREAL_NVP( y ), CEREAL_NVP( z ), CEREAL_NVP( ints ) );
  }

  // Add one element to the private vector
  void populateVector( const int value ) {
    ints.push_back( value );
  }
};

int main()
{
  MyClass  MyObject{};

  MyObject.populateVector( 101 );
  MyObject.populateVector( 202 );
  MyObject.populateVector( 303 );

  // For brevity I just print the serialization to the standard output instead of the binary file
  cereal::JSONOutputArchive oarchive( cout );
  oarchive( MyObject );

  return 0;
}

此代码应发出以下输出:

代码语言:javascript
复制
{
    "value0": {
        "x": 0,
        "y": 0,
        "z": 0,
        "ints": [
            101,
            202,
            303
        ]
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46966307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档