我是使用 boost 序列化库的新手。
我想使用 text_iarchive 和 text_oarchive 在 STL 结构中保存和加载数据。
在map
、list
、deque
、set
和vector
上有除了在 queue
和 stack
上没有任何问题,我收到以下错误:
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
andsave
functions cannot be put with the containers in their declaring namespace, because that's the::std
namespace.
修复
在默认情况下,这意味着您需要包含 deque
的序列化之前 stack
或 queue
:
#include <boost/serialization/deque.hpp>
#include <boost/serialization/stack.hpp>
#include <boost/serialization/queue.hpp>
#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/