Created
April 11, 2024 16:46
-
-
Save dpiponi/6f57a3d5ac5c2fe841b955a5dd5855ac to your computer and use it in GitHub Desktop.
De/serialization in C++ (not suitable when typeid not consistent)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <map> | |
template<typename T> | |
void ReadAndConsume(std::istringstream& s) | |
{ | |
T t; | |
s >> t; | |
std::cout << t << ' '; | |
} | |
template<typename...Ts> | |
struct DispatchTable | |
{ | |
inline static std::map<size_t, void(*)(std::istringstream&)> | |
Entries{{typeid(Ts).hash_code(), &ReadAndConsume<Ts>}...}; | |
}; | |
int main() | |
{ | |
typedef DispatchTable<float, int> Table; | |
std::ostringstream t; | |
t << typeid(int).hash_code() << ' ' << 17 << ' '; | |
t << typeid(float).hash_code() << ' ' << 3.14 << ' '; | |
std::istringstream u(t.str()); | |
for (int i = 0; i < 2; ++i) | |
{ | |
size_t id; | |
u >> id; | |
Table::Entries[id](u); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment