boost序列化的编译错误

Compilation error with boost serialization

本文关键字:错误 编译 序列化 boost      更新时间:2023-10-16

我创建了一个小样本来测试boost序列化库,但是我有一个编译问题。

首先,下面是代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <boost/filesystem/operations.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/version.hpp>
std::vector<uint8_t> buf;
class MyClass
{
public:
    MyClass(){};
    virtual ~MyClass(){};
    int assetStatus;
    friend class boost::serialization::access;
    template<typename Archive> void serialize(
        Archive & ar,
        const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(assetStatus);
    }
    std::string ToString()
    {
        std::string toret;
        toret += " assetStatus: " + assetStatus;
        return toret;
    }
};
int main()
{
    MyClass a, b;
    a.assetStatus = 10;
    std::cout << a.ToString();
    boost::archive::xml_oarchive ooxml(std::ofstream(dbPath));
    ooxml << BOOST_SERIALIZATION_NVP(a); // error here
    MyClass d;
    boost::archive::xml_iarchive iixml(std::ifstream(dbPath));
    iixml >> BOOST_SERIALIZATION_NVP(d); // error here
    std::cout << d.ToString();
}

我得到一个编译错误在行:

ooxml << BOOST_SERIALIZATION_NVP(a);

iixml >> BOOST_SERIALIZATION_NVP(d);

错误是:

'iixml >> boost::serialization::make_nvp(const char*, T&) [with T=MyClass(((MyClass&)(&d)))]'operator>>不匹配

你知道这是什么意思吗?

看起来dbPath没有定义。此外,ooxml/iixml的声明似乎不正确。

试着修改你的代码做下面的事情:…

const char * dbPath = "file.xml"
std::ofstream ofs(dbPath);
boost::archive::xml_oarchive ooxml(ofs);
ooxml << BOOST_SERIALIZATION_NVP(a); 
std::ifstream ifs(dbPath);
boost::archive::xml_iarchive iixml(ofs);
iixml >> BOOST_SERIALIZATION_NVP(d); 

我认为NVP(名称值对)不支持读取(即使用iixml),要么使用&(而不是>>)或iixml>> d;