non_def_con_class.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 <cassert>
  10. #include <memory>
  11. #include <iostream>
  12. #include <msgpack.hpp>
  13. struct my {
  14. my() = delete;
  15. // target class should be either copyable or movable (or both).
  16. my(my const&) = delete;
  17. my(my&&) = default;
  18. my(int a):a(a) {}
  19. int a;
  20. MSGPACK_DEFINE(a);
  21. };
  22. namespace msgpack {
  23. MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
  24. namespace adaptor {
  25. template<>
  26. struct as<my> {
  27. my operator()(msgpack::object const& o) const {
  28. if (o.type != msgpack::type::ARRAY) throw msgpack::type_error();
  29. if (o.via.array.size != 1) throw msgpack::type_error();
  30. return my(o.via.array.ptr[0].as<int>());
  31. }
  32. };
  33. } // namespace adaptor
  34. } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
  35. } // namespace msgpack
  36. int main() {
  37. my m1(42);
  38. msgpack::zone z;
  39. msgpack::object obj(m1, z);
  40. std::cout << obj << std::endl;
  41. assert(m1.a == obj.as<my>().a);
  42. }