[英]How to serialize property using boost?
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
struct Foo {
int x_, y, z;
int get_x() const { return x_; }
void put_x(int v) { x_ = v; }
__declspec(property(get = get_x, put = put_x)) int x;
void serialize(auto& ar, unsigned) {
ar& x; // THIS NOT WORK
ar& y& z;
}
};
std::ofstream ofs("file.txt");
boost::archive::binary_oarchive oa(ofs);
oa << Foo{ 1, 2, 3 };
std::ifstream ifs("file.txt");
boost::archive::binary_iarchive ia(ifs);
Foo foo;
ia >> foo;
Is is possible to serialize __descspec property?是否可以序列化 __descspec 属性?
You can serialize the underlying field.您可以序列化基础字段。
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <iostream>
#include <sstream>
struct S {
void put_x(int val) { _x = val; }
int get_x() const { return _x; }
#ifdef _MSC_VER
__declspec(property(get = get_x, put = put_x)) int the_prop;
#endif
private:
friend class boost::serialization::access;
template <typename Ar> void serialize(Ar& ar, unsigned) { ar& _x; }
int _x;
};
int main() {
std::stringstream ss;
{
S s;
#ifdef _MSC_VER
s.the_prop = 42;
#else
s.put_x(42);
#endif
boost::archive::text_oarchive(ss) << s;
}
std::cout << "Archive contents: " << ss.str() << "\n";
{
S s;
boost::archive::text_iarchive(ss) >> s;
#ifdef _MSC_VER
std::cout << "Deserialized: " << s.the_prop << "\n";
#else
std::cout << "Deserialized: " << s.get_x() << "\n";
#endif
}
}
Prints印刷
Archive contents: 22 serialization::archive 19 0 0 42
Deserialized: 42
See it Live On GCC现场观看 GCC
See it Compiling on MSVC请参阅在 MSVC 上编译
UPDATE And Live On MSVC更新并在 MSVC 上运行
Since Foo won't use get_x, return x_ as reference.由于 Foo 不会使用 get_x,因此返回 x_ 作为参考。
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
struct Foo {
int x_, y, z;
int& get_x() { return x_; }
void put_x(int v) { x_ = v; }
__declspec(property(get = get_x, put = put_x)) int x;
void serialize(auto& ar, unsigned) {
ar& x; // IT WORKS
ar& y& z;
}
};
int main()
{
{
std::ofstream ofs("file.txt");
boost::archive::binary_oarchive oa(ofs);
oa << Foo{ 1, 2, 3 };
} {
std::ifstream ifs("file.txt");
boost::archive::binary_iarchive ia(ifs);
Foo foo;
ia >> foo;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.