-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerializer.hpp
76 lines (64 loc) · 2.04 KB
/
Serializer.hpp
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
/*
* Serializer.h
*
* Created on: Aug 16, 2019
* Author: sakex
*/
#ifndef SERIALIZER_SERIALIZER_H_
#define SERIALIZER_SERIALIZER_H_
#include "Serializable.h"
#include <fstream>
#include <string>
#include <iostream>
#include <type_traits>
/// Serializer namespace
namespace Serializer {
/**
* Static method to check if a class implements Serializable
* @tparam Serializable
*/
template<bool Serializable>
struct is_serializable {
};
/// If is not serializable, try to use the ofstream overload
template<>
struct is_serializable<false> {
static void to_file(std::string const &output, std::string const &file_name) {
std::ofstream file(file_name);
file << output;
file.close();
}
};
/// If serializable, run to_file function with to_string() implementation
template<>
struct is_serializable<true> {
template<typename T>
static void to_file(T *serializable, std::string const &file_name) {
std::string output = serializable->to_string();
is_serializable<false>::to_file(output, file_name);
}
};
/**
* Exports to file from pointer
*
* @tparam T Type of the object to be serialized
* @param to_print Pointer to the object to be serialized
* @param file_name File to which the string should be written
*/
template<typename T>
void to_file(T *to_print, std::string const &file_name) {
is_serializable<std::is_base_of<Serializable, T>::value>::to_file(to_print, file_name);
}
/**
* Exports to file from value
*
* @tparam T Type of the object to be serialized
* @param to_print Object to be serialized
* @param file_name File to which the string should be written
*/
template<typename T>
void to_file(T to_print, std::string const &file_name) {
is_serializable<std::is_base_of<Serializable, T>::value>::to_file(to_print, file_name);
}
} /* namespace Serializer */
#endif /* SERIALIZER_SERIALIZER_H_ */