Skip to content

Commit 9a2bb0c

Browse files
author
Martin C Drohmann
committed
demonstrate the motivation behind the previous patch
1 parent 7191a3b commit 9a2bb0c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

example/cpp11/non_def_con_class.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ struct my {
2323
my(int a):a(a) {}
2424
int a;
2525
MSGPACK_DEFINE(a);
26+
27+
bool operator==(const my & other) const
28+
{
29+
return other.a == a;
30+
}
31+
32+
bool operator<(const my & other) const
33+
{
34+
return other.a > a;
35+
}
2636
};
2737

2838
namespace msgpack {
@@ -48,4 +58,34 @@ int main() {
4858
msgpack::object obj(m1, z);
4959
std::cout << obj << std::endl;
5060
assert(m1.a == obj.as<my>().a);
61+
62+
// useful keys for maps do not have as<>() method implemented:
63+
std::cout << "has_as<int> " << msgpack::has_as<int>::value << std::endl;
64+
std::cout << "has_as<string> " << msgpack::has_as<std::string>::value << std::endl;
65+
66+
// BEFORE PATCH: as a result as<map<K, V> >() is not available either.
67+
// AFTER PATCH: as<map<K, V> >() is available if key OR value have an as<>() implementation
68+
std::cout << "has_as<std::map<int, my> > " << msgpack::has_as<std::map<int, my> >::value << std::endl;
69+
70+
std::map<int, my> m;
71+
m.emplace(1, my(17));
72+
msgpack::object obj2(m, z);
73+
std::cout << obj2 << std::endl;
74+
75+
// BEFORE PATCH: this makes the following break with a compiler error,
76+
// beacuse it uses the deleted my:my() constructor, as it falls back to the
77+
// convert() method.
78+
// AFTER PATCH: the following works and uses the customary as() implementation
79+
assert(m == obj2.as<decltype(m)>());
80+
81+
std::map<my, int> m2;
82+
m2.emplace(17, 42);
83+
msgpack::object obj3(m2, z);
84+
std::cout << obj3 << std::endl;
85+
86+
// BEFORE PATCH: this makes the following break with a compiler error:
87+
// beacuse it uses the deleted my:my() constructor, as it falls back to the
88+
// convert() method.
89+
// AFTER PATCH: the following works and uses the customary as() implementation
90+
assert(m2 == obj3.as<decltype(m2)>());
5191
}

0 commit comments

Comments
 (0)