c++ - 使用 boost 库在队列和堆栈数据结构上保存和加载数据时出错

标签 c++ boost stl

我是使用 boost 序列化库的新手。

我想使用 text_iarchive 和 text_oarchive 在 STL 结构中保存和加载数据。

maplistdequesetvector上有除了在 queuestack 上没有任何问题,我收到以下错误:

error: no matching function for call to 'save(boost::archive::text_oarchive&, const std::deque<PKT_UNIT, std::allocator<PKT_UNIT> >&, const unsigned int&)' 
error: no matching function for call to 'load(boost::archive::text_iarchive&, std::deque<PKT_UNIT, std::allocator<PKT_UNIT> >&, const unsigned int&)'

我为此使用了以下代码:

mystruct test;
test.initial();
{
    std::ofstream ofs("filename.dat");
    boost::archive::text_oarchive ar(ofs);
    ar & test;
}
{
    std::ifstream ifs("filename.dat");
    boost::archive::text_iarchive ar(ifs);
    mystruct restored;
    ar & restored;
}

我该如何解决这个问题?

最佳答案

堆栈和队列不是容器。它们是容器适配器。

根据设计,它们不会向底层容器公开原始访问权限,但底层容器可序列化的标准库容器(默认情况下为 vector<>deque<>分别)。

Boost 序列化使用派生类的技巧来访问 the underlying container ::c .

由于围绕精确实例化点规则和模板顺序的技术细节,底层容器的序列化代码在容器的序列化代码之前可见(声明)至关重要适配器。

In fact, clang has a very apt message here:

boost/serialization/queue.hpp|40 col 9| error: call to function 'save' that is neither visible in the template definition nor found by argument-dependent lookup

The problem, of course, being triggered by the fact that the load and save functions cannot be put with the containers in their declaring namespace, because that's the ::std namespace.

修复

在默认情况下,这意味着您需要包含 deque 的序列化之前 stackqueue :

#include <boost/serialization/deque.hpp>

#include <boost/serialization/stack.hpp>
#include <boost/serialization/queue.hpp>

Live On Coliru

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include <boost/serialization/deque.hpp>

#include <boost/serialization/stack.hpp>
#include <boost/serialization/queue.hpp>

struct mystruct {
    std::stack<int> _s;
    std::queue<int> _q;

    void foo() {
        _s.push(1); _s.push(2); _s.push(3);
        _q.push(1); _q.push(2); _q.push(3);
    }

    template <typename Ar> void serialize(Ar& ar, unsigned /*version*/) { ar & _s & _q; }
};

#include <fstream>

int main() {
    {
        mystruct test;

        std::ofstream ofs("filename.dat");
        boost::archive::text_oarchive oa(ofs);
        oa << test;
    }
    {
        std::ifstream ifs("filename.dat");
        boost::archive::text_iarchive ia(ifs);
        mystruct restored;
        ia >> restored;
    }
}

filename.dat包含

 1  22 serialization::archive 15 0 0 0 0 0 0

在现场演示中

关于c++ - 使用 boost 库在队列和堆栈数据结构上保存和加载数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475948/

相关文章:

c++ - 如何将数字转换为十进制字符串?

c++ - 简单的 C++ vector/指针失误

c++ - sizeof(some pointer) 是否总是等于四?

c++ - boost::write_graphviz - 如何水平生成图形

c++ - Eclipse 上的 Autotools 项目和外部库

c++ - 可调用到 std::bind 的类型

c++ - 使用 boost_any 时是否可以避免开销?

c++ - STL 容器和内存管理——对象列表与对象指针列表

c++ - 如何使用 `llvm::ilist_iterator<NodeTy>::operator pointer() const` 方法?

c++ - 使用 STL 数字的意外参数传递顺序