Skip to content

Instantly share code, notes, and snippets.

@ghtz08
Created June 20, 2022 08:31
Show Gist options
  • Save ghtz08/042e8acb3844e23f3c9aeababd0dd810 to your computer and use it in GitHub Desktop.
Save ghtz08/042e8acb3844e23f3c9aeababd0dd810 to your computer and use it in GitHub Desktop.
简易的 format
namespace details {
template <size_t fmt_len, typename... Args>
struct format_to_h;
template <size_t fmt_len, typename Arg, typename... Args>
struct format_to_h<fmt_len, Arg, Args...> {
auto operator()(std::ostream & out, char const (&fmt)[fmt_len], size_t fmt_start, Arg && arg, Args && ... args) -> void {
auto const braces = std::strstr(&fmt[fmt_start], "{}");
if (braces == nullptr) {
format_to_h<fmt_len>()(out, fmt, fmt_start);
return;
}
out.write(&fmt[fmt_start], braces - &fmt[fmt_start]);
out << std::forward<Arg>(arg);
format_to_h<fmt_len, Args...>()(out, fmt, (braces + 2) - fmt, std::forward<Args>(args)...);
}
};
template <size_t fmt_len>
struct format_to_h<fmt_len> {
auto operator()(std::ostream & out, char const (&fmt)[fmt_len], size_t fmt_start) -> void {
out.write(&fmt[fmt_start], (fmt_len - 1) - fmt_start);
}
};
} // namespace details
template <size_t fmt_len, typename... Args>
auto format_to(std::ostream & out, char const (&fmt)[fmt_len], Args && ... args) -> void {
details::format_to_h<fmt_len, Args...>()(
out, fmt, 0, std::forward<Args>(args)...);
}
template <size_t fmt_len, typename... Args>
auto format(char const (&fmt)[fmt_len], Args && ... args) -> std::string {
auto oss = std::ostringstream();
format_to(oss, fmt, std::forward<Args>(args)...);
return oss.str();
}
template <size_t fmt_len, typename... Args>
auto print(char const (&fmt)[fmt_len], Args && ... args) -> void {
format_to(std::cout, fmt, std::forward<Args>(args)...);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment