Skip to content

Instantly share code, notes, and snippets.

@yangacer
Created July 24, 2019 08:30
Show Gist options
  • Save yangacer/75d5eb05e5db7ce2732408f3c88d3e3f to your computer and use it in GitHub Desktop.
Save yangacer/75d5eb05e5db7ce2732408f3c88d3e3f to your computer and use it in GitHub Desktop.
C++14 De/serialization structures made simple
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
template <size_t First, size_t Last>
struct ReadAux {
template <typename Tuple>
static auto& Exec(std::istream& os, Tuple&& args) {
os >> std::get<First>(args);
return ReadAux<First + 1, Last>::Exec(os, std::forward<Tuple>(args));
}
};
template <size_t Last>
struct ReadAux<Last, Last> {
template <typename Tuple>
static auto& Exec(std::istream& os, Tuple&& args) {
return os >> std::get<Last>(args);
}
};
template <typename Tuple>
auto& operator>>(std::istream& os, Tuple&& args) {
constexpr size_t size = std::tuple_size<Tuple>::value;
return ReadAux<0, size - 1>::Exec(os, std::forward<Tuple>(args));
}
template <size_t First, size_t Last>
struct WriteAux {
template <typename Tuple>
static auto& Exec(std::ostream& os, Tuple&& args) {
os << std::get<First>(args) << ", ";
return WriteAux<First + 1, Last>::Exec(os, std::forward<Tuple>(args));
}
};
template <size_t Last>
struct WriteAux<Last, Last> {
template <typename Tuple>
static auto& Exec(std::ostream& os, Tuple&& args) {
return os << std::get<Last>(args);
}
};
template <typename Tuple>
auto& operator<<(std::ostream& os, Tuple&& args) {
constexpr size_t size = std::tuple_size<Tuple>::value;
return WriteAux<0, size - 1>::Exec(os, std::forward<Tuple>(args));
}
// --- client
struct S {
int num = 123;
std::string str = "abc";
auto members() const { return std::tie(num, str); }
auto members() { return std::tie(num, str); }
};
int main() {
std::stringstream ss;
// avoid ambiguous overloading
ss.write("123 abc", 7);
S s;
ss >> s.members();
std::cout << s.members() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment