Compilation error with boost serialization

1.2k Views Asked by At

I created a small sample for testing the boost serialization library, but I have a compilation problem.

First of all, here's the code:

#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();
}

I get a compilation error at the lines:

ooxml << BOOST_SERIALIZATION_NVP(a);

and

iixml >> BOOST_SERIALIZATION_NVP(d);

The error is:

no match for operator>> in 'iixml >> boost::serialization::make_nvp(const char*, T&) [with T=MyClass(((MyClass&)(&d)))]'

Do you have any idea regarding the meaning of this?

2

There are 2 best solutions below

1
On BEST ANSWER

It looks like dbPath is not defined. Additionally, the declaration of ooxml/iixml appears incorrect.

Try modifying your code to do the following: ...

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); 
0
On

I think NVP (name value pair) is not supported for reading (i.e. with iixml), either use & (instead of >>) or iixml >> d;