Skip to content

Instantly share code, notes, and snippets.

@dpiponi
Created April 11, 2024 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpiponi/6f57a3d5ac5c2fe841b955a5dd5855ac to your computer and use it in GitHub Desktop.
Save dpiponi/6f57a3d5ac5c2fe841b955a5dd5855ac to your computer and use it in GitHub Desktop.
De/serialization in C++ (not suitable when typeid not consistent)
#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