Created
May 3, 2019 20:26
-
-
Save parsa/3beff8ccf16979ab94524e0713a11897 to your computer and use it in GitHub Desktop.
Poor Man's fmt
This file contains hidden or 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 <exception> | |
#include <iostream> | |
#include <sstream> | |
#include <string> | |
template <typename... Ts> | |
std::string tprintf(char const* format, Ts... vs); | |
template <typename E=std::runtime_error, typename... Ts> | |
inline std::exception formatted_exception(Ts... vs) | |
{ | |
auto r = tprintf(std::forward<Ts>(vs)...); | |
return E{r}; | |
} | |
std::stringstream& sstprintf(std::stringstream& ss, char const* format) | |
{ | |
ss << format; | |
return ss; | |
} | |
template <typename T, typename... Targs> | |
std::stringstream& sstprintf( | |
std::stringstream& ss, char const* format, T value, Targs... Fargs) | |
{ | |
for (; *format != '\0'; ++format) | |
{ | |
if (*format == '%') | |
{ | |
ss << value; | |
tprintf(format + 1, Fargs...); | |
return ss; | |
} | |
ss << *format; | |
} | |
return ss; | |
} | |
template <typename... Ts> | |
std::string tprintf(char const* format, Ts... vs) | |
{ | |
std::stringstream ss; | |
sstprintf(ss, format, std::forward<Ts>(vs)...); | |
return ss.str(); | |
} | |
int main() | |
{ | |
try | |
{ | |
throw formatted_exception("message"); | |
} | |
catch (std::exception const& e) | |
{ | |
std::cout << "exception: " << e.what() << "\n"; | |
} | |
std::cout << "end of execution\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment