Created
September 21, 2012 09:34
-
-
Save toffaletti/3760605 to your computer and use it in GitHub Desktop.
basic C++11 string formatting
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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ g++-4.7 -Wall -ggdb -std=c++11 format.cc
$ ./a.out
welcome foo bar = 1.3