Skip to content

Instantly share code, notes, and snippets.

@jepio
Created November 1, 2015 10:29
Show Gist options
  • Save jepio/ba0219c4c53eb68769ed to your computer and use it in GitHub Desktop.
Save jepio/ba0219c4c53eb68769ed to your computer and use it in GitHub Desktop.
variadic vs. monadic(?) binary write
#include <iostream>
#include <fstream>
template <typename... Ts>
void ignore(Ts&&...) {}
template <class Stream, typename T>
void write(Stream& s, T&& t)
{
s.write(reinterpret_cast<const char *>(&t), sizeof(T));
}
template <class Stream, typename... Vs>
auto write(Stream& s, Vs&&... vs)
-> decltype(void(s.write(nullptr, 0)))
{
(void)std::initializer_list<int>{(write(s, vs), 0)...};
}
int main()
{
std::ofstream file{"filename", std::ios::binary};
auto write_to = [](auto& f) {
return [&f](auto g) {
return g(f);
};
};
auto arg = [write_to](auto&& val) {
return [=](auto& f) {
f.write(reinterpret_cast<const char *>(&val), sizeof(val));
return write_to(f);
};
};
write_to(file)(arg(72))(arg(69))(arg(89))(arg(0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment