在提升巴士时间表示例代码中 bus schedule sample 我尝试反序列化char数组中的数据。所以我添加了这个功能。但它有这个错误。有什么问题?
void frombuffer_schedule(char* buffer,const bus_schedule& obj)
{
boost::iostreams::stream<boost::iostreams::array_source> is(buffer, 4096);
boost::archive::binary_iarchive ia(is,boost::archive::archive_flags::no_header);
ia >> obj;
}
错误是“错误:静态断言失败:typex :: value”
答案 0 :(得分:0)
您正在反序列化为const
对象。这是失败断言的实际代码:
// cannot load data into a "const" object unless it's a
// wrapper around some other non-const object.
BOOST_STATIC_ASSERT(typex::value);
所以,解决它:)
<强> Live On Coliru 强>
#include <boost/serialization/string.hpp>
#include <boost/serialization/serialization.hpp>
struct MyData {
std::string s;
float values[7];
private:
friend class boost::serialization::access;
template <typename Ar>
void serialize(Ar& ar, unsigned) { ar & s & values; }
};
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
namespace bio = boost::iostreams;
std::vector<char> to_buffer(const MyData& obj) {
std::vector<char> buffer;
bio::stream<bio::back_insert_device<std::vector<char> > > os(buffer);
namespace ba = boost::archive;
ba::binary_oarchive oa(os, ba::archive_flags::no_header);
oa << obj;
return buffer;
}
void from_buffer(char* buffer, MyData& obj) {
bio::stream<bio::array_source> is(buffer, 4096);
namespace ba = boost::archive;
ba::binary_iarchive ia(is, ba::archive_flags::no_header);
ia >> obj;
}
#include <iostream>
#include <iomanip>
static inline std::ostream& operator<<(std::ostream& os, MyData const& object) {
os << "s:" << std::quoted(object.s) << ", values:[";
for (float v : object.values)
os << " " << v;
return os << " ]";
}
int main() {
auto buffer = to_buffer(MyData { "hello world", { 1,2,3,4,5,6,7 } });
MyData received;
from_buffer(buffer.data(), received);
std::cout << "Received: " << received << "\n";
}
打印
Received: s:"hello world", values:[ 1 2 3 4 5 6 7 ]