Created
November 1, 2015 10:29
-
-
Save jepio/ba0219c4c53eb68769ed to your computer and use it in GitHub Desktop.
variadic vs. monadic(?) binary write
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 <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