Last active
May 24, 2021 07:50
-
-
Save cleoold/0f992b0fdee7dc3d6d0ed4497044d261 to your computer and use it in GitHub Desktop.
a dirty enough string.format() function for pre-c++20 for copy pasta
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
// string format | |
// by cos 2020. licensed under MIT | |
#pragma once | |
#include <string> | |
#include <sstream> | |
namespace detail { | |
template<class CharT> | |
void format_impl(std::basic_ostringstream<CharT> &oss, const CharT *s) { | |
oss << s; | |
} | |
template<class CharT, class V, class ...Args> | |
void format_impl(std::basic_ostringstream<CharT> &oss, const CharT *s, const V &v, const Args& ...args) { | |
while (*s) { | |
// if have input like "{{haha", where there is a left brace not followed by a right brace, | |
// ignore this | |
if (*s == '{' && *(s+1) == '}') { | |
oss << v; | |
return format_impl(oss, (s+2), args...); | |
} | |
oss << *s++; | |
} | |
throw std::runtime_error("extra arguments provided to format"); | |
} | |
} | |
/** | |
* simple string.format. usage: format("hello {}th {}!", 5, "Alice") | |
* produces "hello 5th Alice!" | |
*/ | |
template<class CharT, class ...Args> | |
std::basic_string<CharT> format(const CharT *s, const Args& ...args) { | |
std::basic_ostringstream<CharT> oss; | |
detail::format_impl(oss, s, args...); | |
return oss.str(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment