-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
93 lines (75 loc) · 2.42 KB
/
main.cpp
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
93
#include <cereal/archives/json.hpp>
#include <cereal/cereal.hpp>
#include <cereal/types/chrono.hpp>
#include <chrono>
#include <iostream>
namespace demo {
class TemperatureSample {
public:
TemperatureSample() = default;
explicit TemperatureSample(double temperature) : m_temperature(temperature) {}
TemperatureSample(std::chrono::system_clock::time_point time,
double temperature)
: m_time(time), m_temperature(temperature) {}
void Time(const std::chrono::system_clock::time_point &time) {
m_time = time;
}
[[nodiscard]] std::chrono::system_clock::time_point Time() const {
return m_time;
}
void Temperature(const double temperature) { m_temperature = temperature; }
[[nodiscard]] double Temperature() const { return m_temperature; }
private:
std::chrono::system_clock::time_point m_time =
std::chrono::system_clock::now();
double m_temperature = 0.0;
};
std::ostream &operator<<(std::ostream &os, const TemperatureSample &ts) {
os << "Time: " << ts.Time().time_since_epoch().count()
<< "; Temperature: " << ts.Temperature() << std::endl;
return os;
}
template <class Archive>
void save(Archive &archive, TemperatureSample const &obj) {
archive(cereal::make_nvp("m_time", obj.Time()),
cereal::make_nvp("m_temperature", obj.Temperature()));
}
template <class Archive> void load(Archive &archive, TemperatureSample &obj) {
std::chrono::system_clock::time_point tmp_time{};
double tmp_temp{};
archive(cereal::make_nvp("m_time", tmp_time),
cereal::make_nvp("m_temperature", tmp_temp));
TemperatureSample tmp{tmp_time, tmp_temp};
obj = tmp;
}
} // namespace
int main() {
std::stringstream os{};
{
cereal::JSONOutputArchive ar{os};
std::cout << "Serializing:" << std::endl;
for (auto i = 0; i < 10; i++) {
demo::TemperatureSample sample{static_cast<double>(i)};
std::cout << sample << std::endl;
ar(sample);
}
}
{
cereal::JSONInputArchive ar{os};
std::cout << "Deserializing:" << std::endl;
bool continue_reading = true;
while (continue_reading) {
demo::TemperatureSample sample{};
try {
ar(sample);
std::cout << sample << std::endl;
} catch(const cereal::RapidJSONException& e) {
std::ignore = e;
continue_reading = false;
}
}
}
std::cout << "The JSON file looked like this: " << std::endl
<< os.str() << std::endl;
return 0;
}