class_intrusive_map.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // MessagePack for C++ example
  2. //
  3. // Copyright (C) 2015 KONDO Takatoshi
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. #include <string>
  10. #include <iostream>
  11. #include <iomanip>
  12. #include <sstream>
  13. #include <cassert>
  14. #include <msgpack.hpp>
  15. class my_class {
  16. public:
  17. my_class() {} // When you want to convert from msgpack::object to my_class,
  18. // my_class should be default constractible.
  19. // If you use C++11, you can adapt non-default constructible
  20. // classes to msgpack::object.
  21. // See https://github.com/msgpack/msgpack-c/wiki/v1_1_cpp_adaptor#non-default-constructible-class-support-c11-only
  22. my_class(std::string const& name, int age):name_(name), age_(age) {}
  23. friend bool operator==(my_class const& lhs, my_class const& rhs) {
  24. return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
  25. }
  26. private:
  27. std::string name_;
  28. int age_;
  29. public:
  30. MSGPACK_DEFINE_MAP(name_, age_);
  31. };
  32. void print(std::string const& buf) {
  33. for (std::string::const_iterator it = buf.begin(), end = buf.end();
  34. it != end;
  35. ++it) {
  36. std::cout
  37. << std::setw(2)
  38. << std::hex
  39. << std::setfill('0')
  40. << (static_cast<int>(*it) & 0xff)
  41. << ' ';
  42. }
  43. std::cout << std::dec << std::endl;
  44. }
  45. int main() {
  46. { // pack, unpack
  47. my_class my("John Smith", 42);
  48. std::stringstream ss;
  49. msgpack::pack(ss, my);
  50. print(ss.str());
  51. msgpack::object_handle oh =
  52. msgpack::unpack(ss.str().data(), ss.str().size());
  53. msgpack::object obj = oh.get();
  54. std::cout << obj << std::endl;
  55. assert(obj.as<my_class>() == my);
  56. }
  57. { // create object with zone
  58. my_class my("John Smith", 42);
  59. msgpack::zone z;
  60. msgpack::object obj(my, z);
  61. std::cout << obj << std::endl;
  62. assert(obj.as<my_class>() == my);
  63. }
  64. }