mirror of
https://github.com/msgpack/msgpack-c.git
synced 2025-10-13 22:50:19 +02:00
Added an example of the non default constructible class.
Refined an intrusive example. It includes base class serialization. We can switch map based and array based serialization.
This commit is contained in:
@@ -21,17 +21,42 @@
|
||||
#include <sstream>
|
||||
#include <cassert>
|
||||
|
||||
#if 0 // When you want to adapt map instead of array, you can enable these macro definition.
|
||||
#define MSGPACK_USE_DEFINE_MAP
|
||||
#define MSGPACK_USE_BOOST
|
||||
#endif
|
||||
|
||||
#include <msgpack.hpp>
|
||||
|
||||
struct my_base1 {
|
||||
int a;
|
||||
MSGPACK_DEFINE(a);
|
||||
};
|
||||
inline bool operator==(my_base1 const& lhs, my_base1 const& rhs) {
|
||||
return lhs.a == rhs.a;
|
||||
}
|
||||
|
||||
class my_class {
|
||||
struct my_base2 {
|
||||
std::string b;
|
||||
std::string c;
|
||||
MSGPACK_DEFINE(b, c);
|
||||
};
|
||||
inline bool operator==(my_base2 const& lhs, my_base2 const& rhs) {
|
||||
return lhs.b == rhs.b && lhs.c == rhs.c;
|
||||
}
|
||||
|
||||
class my_class : public my_base1, private my_base2 {
|
||||
public:
|
||||
my_class() {} // When you want to convert from msgpack::object to my_class,
|
||||
// my_class should be default constractible.
|
||||
my_class(std::string const& name, int age):name_(name), age_(age) {}
|
||||
|
||||
void set_b(std::string const& str) { b = str; }
|
||||
void set_c(std::string const& str) { c = str; }
|
||||
friend bool operator==(my_class const& lhs, my_class const& rhs) {
|
||||
return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
|
||||
return
|
||||
static_cast<my_base1 const&>(lhs) == static_cast<my_base1 const&>(rhs) &&
|
||||
static_cast<my_base2 const&>(lhs) == static_cast<my_base2 const&>(rhs) &&
|
||||
lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -39,7 +64,7 @@ private:
|
||||
int age_;
|
||||
|
||||
public:
|
||||
MSGPACK_DEFINE(name_, age_);
|
||||
MSGPACK_DEFINE(name_, age_, MSGPACK_BASE(my_base1), MSGPACK_BASE(my_base2));
|
||||
};
|
||||
|
||||
void print(std::string const& buf) {
|
||||
@@ -59,6 +84,9 @@ void print(std::string const& buf) {
|
||||
int main() {
|
||||
{ // pack, unpack
|
||||
my_class my("John Smith", 42);
|
||||
my.a = 123;
|
||||
my.set_b("ABC");
|
||||
my.set_c("DEF");
|
||||
std::stringstream ss;
|
||||
msgpack::pack(ss, my);
|
||||
|
||||
@@ -72,6 +100,8 @@ int main() {
|
||||
}
|
||||
{ // create object with zone
|
||||
my_class my("John Smith", 42);
|
||||
my.set_b("ABC");
|
||||
my.set_c("DEF");
|
||||
msgpack::zone z;
|
||||
msgpack::object obj(my, z);
|
||||
std::cout << obj << std::endl;
|
||||
|
Reference in New Issue
Block a user