Last active
June 7, 2020 06:46
-
-
Save justinvh/7426137 to your computer and use it in GitHub Desktop.
C++11 _format suffix literal for .format() like string arguments.
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 <string> | |
#include <vector> | |
#include <sstream> | |
#include <exception> | |
namespace std { | |
std::string to_string(const char* value) | |
{ | |
return std::string(value); | |
} | |
} | |
struct StringFormat { | |
std::string fmt; | |
std::vector<std::string> arguments; | |
StringFormat(std::string fmt) | |
: fmt(fmt) {} | |
template <typename T, typename ...Tail> | |
std::string operator()(const T& t, Tail&&... tail) | |
{ | |
arguments.push_back(std::to_string(t)); | |
return operator()(std::forward<Tail>(tail)...); | |
} | |
std::string operator()() | |
{ | |
size_t found = 0; | |
const std::string grep = "{}"; | |
auto arg_begin = arguments.cbegin(); | |
auto arg_end = arguments.cend(); | |
while ((found = fmt.find(grep, found)) != std::string::npos) { | |
if (arg_begin == arg_end) | |
throw std::range_error{"args out of range for '{}'"}; | |
fmt.replace(found, grep.size(), *arg_begin); | |
++arg_begin; | |
} | |
return fmt; | |
} | |
}; | |
StringFormat operator"" _format (const char* fmt, size_t len) | |
{ | |
return StringFormat(fmt); | |
} | |
int main() | |
{ | |
std::cout << "Hello {}! You're {} years old.\n"_format("Justin", 23); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment