-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolver.cpp
More file actions
68 lines (55 loc) · 1.75 KB
/
Copy pathresolver.cpp
File metadata and controls
68 lines (55 loc) · 1.75 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
#include <string>
#include <theg/serialization.hpp>
#include <theg/serialization/vector_sink.hpp>
#include <theg/serialization/data_source.hpp>
class Entity
{
public:
// Returns some unique identifier of this entity
std::string_view identifier() const;
};
class Database
{
public:
// Returns a pointer to the entity object with the given identifier
const Entity* resolve(std::string_view) const;
};
class Widget
{
// ...
private:
const Entity* m_entity = nullptr; // Raw pointers cannot be serialized by default
};
// Define a resolver that can take care of `const Entity*` pointers.
// Trait functions could also be implemented in `Database` class directly
struct WidgetResolver
{
// During serialization, write the identifier string
template <class Serialization>
void write(const Entity* entity, Serialization serialization)
{
serialization.write(entity->identifier());
}
// During deserialization, read the identifier string and resolve it via the database
template <class Deserialization>
const Entity* read(theg::type_t<const Entity*>, Deserialization deserialization)
{
return database->resolve(deserialization.read(theg::type<std::string>));
}
Database* database = nullptr;
};
static void foo()
{
Database database;
Widget w;
WidgetResolver resolver = { &database };
// Pass the resolver to the serialization
theg::serialization_vector_sink sink;
sink.write(w, &resolver);
// Get the raw bytes at the end of the serialization
std::vector<std::byte> rawBytes = sink.release();
// Store the bytes and read them again, send it across the network or to some other process
// Re-construct the widget using the resolver again
theg::serialization_data_source source(rawBytes.data(), rawBytes.size());
auto w2 = source.read<Widget>(&resolver);
}