c++ - 使用 boost 序列化从 XML 加载类

标签 c++ boost boost-serialization

我尝试从 XML 文件加载一个简单的类,但出现以下错误:

error: no match for 'operator>>' in 'xml >> boost::serialization::make_nvp(const
char*, T&) [with T = Options](((Options&)(& o)))'

这一定是我做错了什么,但我不知道是什么。有人有主意吗?这是我的代码:

#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/serialization/map.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/nvp.hpp>

class Options {
public:
    Options() {
        SetInteger("screenWidth", 1024);
        SetInteger("screenHeight", 768);
    }
    void SetInteger(const std::string& name, int value) {
        integers_[name] = value;
    }
private:
    std::map<std::string, int> integers_;

    friend class boost::serialization::access;
    template<class archive>
    void serialize(archive& ar, const unsigned int version)
    {
        using boost::serialization::make_nvp;
        ar & make_nvp("integers", integers_);
    }
};

int main() {
    Options o;
    std::ofstream ifs("input.xml");
    boost::archive::xml_oarchive xml(ifs);
    xml >> boost::serialization::make_nvp("options", o); // error
}

最佳答案

从你的代码和你正在编写的内容来看,它会导致你试图阅读。在这种情况下,您不应使用 ofstream 和 xml_oarchive,而应使用 ifstreamxml_iarchive

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

....

//for read
std::ifstream ifs("input.xml");
boost::archive::xml_iarchive xmlIn(ifs);
xmlIn >> boost::serialization::make_nvp("options", o); 

//for write
std::ofstream ofs("output.xml");
boost::archive::xml_oarchive xmlOut(ofs);
xmlOut << boost::serialization::make_nvp("options", o); 

关于c++ - 使用 boost 序列化从 XML 加载类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5729061/

相关文章:

c++ - Qt 中的 QDesktopWidget availableGeometry() 无法正常工作,需要垂直滚动才能查看完整图像

c++ - 四舍五入为间隔不均匀的整数

c++ - GUID的唯一性

c++ - 使用带有 STL 容器的 boost.serialization 作为模板参数

xml - 使用命名空间基类 boost 派生类的无效 xml 标记的序列化

c++ - 未在范围内声明的类

boost - 如何使 boost.build 使用特定的编译器安装?

c++ - 初始化静态 boost::unordered_map

c++ - 在 C++ 中访问 boost::variant vector 的元素

c++ - 正确的类型转换以 boost 不同派生类的反序列化