Skip to content

Instantly share code, notes, and snippets.

@toffaletti
Created September 21, 2012 09:34
Show Gist options
  • Save toffaletti/3760605 to your computer and use it in GitHub Desktop.
Save toffaletti/3760605 to your computer and use it in GitHub Desktop.
basic C++11 string formatting
#include <sstream>
#include <iostream>
struct formatter {
std::string format;
formatter(const std::string &format_)
: format(format_) {}
formatter(const formatter &other) = delete;
formatter(formatter &&other)
: format(std::move(other.format)) {}
template <typename Iter, typename Arg, typename ...Args>
void vformat(std::stringstream &ss, Iter &i, Arg arg) {
while (i < std::end(format)) {
switch (*i) {
case '{':
++i; ++i; // eat the '}'
ss << arg;
break;
default:
ss << *i;
++i;
break;
}
}
}
template <typename Iter, typename Arg, typename ...Args>
void vformat(std::stringstream &ss, Iter &i, Arg arg, Args ...args) {
while (i < std::end(format)) {
switch (*i) {
case '{':
++i; ++i; // eat the '}'
ss << arg;
vformat(ss, i, args...);
return;
default:
ss << *i;
++i;
break;
}
}
}
template <typename ...Args>
std::string operator()(Args ...args) {
std::stringstream ss;
auto i = std::begin(format);
vformat(ss, i, args...);
return ss.str();
}
};
formatter operator"" _fmt(const char *p, size_t n) {
return std::move(formatter(std::string(p, n)));
}
int main() {
using namespace std;
cout << "welcome {} {} = {}"_fmt("foo", "bar", 1.3) << endl;
}
@toffaletti
Copy link
Author

$ g++-4.7 -Wall -ggdb -std=c++11 format.cc
$ ./a.out
welcome foo bar = 1.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment