-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathconvert_partial_specialization_test.cpp
More file actions
92 lines (76 loc) · 1.79 KB
/
convert_partial_specialization_test.cpp
File metadata and controls
92 lines (76 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
#include "gtest/gtest.h"
// Base class
class A {
public:
A() = default;
A(int a) : a{a} {}
// virtual load/emit methods
virtual void load(const YAML::Node &node) { a = node["a"].as<int>(); }
virtual YAML::Node emit() const {
YAML::Node node;
node["a"] = a;
return node;
}
int a{};
};
// Derived class
class B : public A {
public:
B() = default;
B(int a, int b) : A{a}, b{b} {}
// override virtual load/emit methods
virtual void load(const YAML::Node &node) override {
A::load(node);
b = node["b"].as<int>();
}
virtual YAML::Node emit() const override {
YAML::Node node = A::emit();
node["b"] = b;
return node;
}
int b{};
};
// Implementation of convert::{encode,decode} for all classes derived from or
// being A
namespace YAML {
template <typename T>
struct convert<T, typename std::enable_if<std::is_base_of<A, T>::value>::type> {
static Node encode(const T &rhs) {
Node node = rhs.emit();
return node;
}
static bool decode(const Node &node, T &rhs) {
rhs.load(node);
return true;
}
};
namespace {
TEST(ConvertPartialSpecializationTest, EncodeBaseClass) {
Node n(Load("{a: 1}"));
A a = n.as<A>();
EXPECT_EQ(a.a, 1);
}
TEST(ConvertPartialSpecializationTest, EncodeDerivedClass) {
Node n(Load("{a: 1, b: 2}"));
B b = n.as<B>();
EXPECT_EQ(b.a, 1);
EXPECT_EQ(b.b, 2);
}
TEST(ConvertPartialSpecializationTest, DecodeBaseClass) {
A a(1);
Node n;
n = a;
EXPECT_EQ(a.a, n["a"].as<int>());
}
TEST(ConvertPartialSpecializationTest, DecodeDerivedClass) {
B b(1, 2);
Node n;
n = b;
EXPECT_EQ(b.a, n["a"].as<int>());
EXPECT_EQ(b.b, n["b"].as<int>());
}
} // namespace
} // namespace YAML