我需要通过网络连接发送存储在std :: list中的数据的动态大小列表。我想使用序列化一次完成此操作,而不是单独发送每个元素。有什么建议么?
boost::serialization
使得这相当容易做到。它免费提供了您需要的std::list
所有机制,您所要做的就是为列表所包含的类型添加支持。(如果它是“标准”类型,那么它也已经存在)
完整示例(从此示例改编而成):
#include <list>
#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
// Provide an implementation of serialize for std::list
#include <boost/serialization/list.hpp>
class foo
{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
// This is the only thing you have to implement to serialize a std::list<foo>
ar & value;
// if we had more members here just & each of them with ar
}
public:
int value;
};
int main() {
std::stringstream out;
// setup a list
std::list<foo> list;
{
const foo f = {-1};
list.push_back(f);
}
// serialize into the stream
{
boost::archive::binary_oarchive oa(out);
oa << list;
}
// read the stream into a newlist
std::list<foo> newlist;
{
boost::archive::binary_iarchive ia(out);
ia >> newlist;
}
std::cout << newlist.front().value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
该操作通过进行“发送”和“接收” std::stringstream
,但是通过您选择的网络API对其进行适配以使其发送和接收应该相当简单。
归档时间: |
|
查看次数: |
2152 次 |
最近记录: |