Refined the non-intrusive example. The target class no longer needs public data members.

This commit is contained in:
Takatoshi Kondo 2014-11-01 22:19:05 +09:00
parent 96c688708c
commit e00b299fe0

View File

@ -14,10 +14,10 @@ namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
object const& operator>> (object const& o, my_class& v); object const& operator>> (msgpack::object const& o, my_class& v);
template <typename Stream> template <typename Stream>
packer<Stream>& operator<< (packer<Stream>& o, my_class const& v); packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v);
} // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
} // namespace msgpack } // namespace msgpack
@ -30,15 +30,19 @@ public:
// my_class should be default constractible. // my_class should be default constractible.
my_class(std::string const& name, int age):name_(name), age_(age) {} my_class(std::string const& name, int age):name_(name), age_(age) {}
// When you want to define a non-intrusive adaptor functions, // my_class should provide getters for the data members you want to pack.
// member variables should be public. std::string get_name() const { return name_; }
int get_age() const { return age_; }
friend bool operator==(my_class const& lhs, my_class const& rhs) {
return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
}
private:
std::string name_; std::string name_;
int age_; int age_;
}; };
inline bool operator==(my_class const& lhs, my_class const& rhs) {
return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
}
// definitions // definitions
@ -46,21 +50,22 @@ namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
inline object const& operator>> (object const& o, my_class& v) { inline object const& operator>> (msgpack::object const& o, my_class& v) {
if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); if (o.type != msgpack::type::ARRAY) throw msgpack::type_error();
if (o.via.array.size != 2) throw msgpack::type_error(); if (o.via.array.size != 2) throw msgpack::type_error();
o.via.array.ptr[0].convert(v.name_); v = my_class(
o.via.array.ptr[1].convert(v.age_); o.via.array.ptr[0].as<std::string>(),
o.via.array.ptr[1].as<int>());
return o; return o;
} }
template <typename Stream> template <typename Stream>
inline packer<Stream>& operator<< (packer<Stream>& o, my_class const& v) { inline packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v) {
// packing member variables as an array. // packing member variables as an array.
o.pack_array(2); o.pack_array(2);
o.pack(v.name_); o.pack(v.get_name());
o.pack(v.age_); o.pack(v.get_age());
return o; return o;
} }