Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <sstream>
- #include <iostream>
- #include <cstdlib>
- //TODO: When the std::regex is implimented, use it
- //#include <regex>
- #include <boost/regex.hpp>
- using namespace std;
- //TODO: When the std::regex is implimented, remove this
- using namespace boost;
- class StringFormat
- {
- public:
- StringFormat(const string& rhs): fmtString(rhs), reg(R"(\{(\d+?)\})"), index() {}
- StringFormat(string&& rhs): fmtString(rhs), reg(R"(\{(\d+?)\})"), index() {}
- template <typename Object>
- void Format(const Object& obj)
- {
- string::const_iterator start=fmtString.begin(), end=fmtString.end();
- smatch what;
- while(regex_search(start, end, what, reg))
- {
- if (atoi(string(what[1].first, what[1].second).c_str()) == index)
- {
- fmtString.replace(what[0].first-fmtString.begin(), what[0].second-what[0].first, toString(obj));
- break;
- }
- start = what[0].second;
- }
- if (start == end)
- {
- throw invalid_argument("You are full of bullshit");
- }
- ++index;
- }
- template <typename Object, typename... Args>
- void Format(const Object& obj, Args... args)
- {
- Format(obj);
- Format(args...);
- }
- string getResult()
- {
- if (regex_search(fmtString, reg))
- throw invalid_argument("You are full of bullshit");
- return fmtString;
- }
- private:
- string fmtString;
- regex reg;
- int index;
- private:
- template <typename Type>
- static string toString(const Type& rhs)
- {
- ostringstream oss;
- oss << rhs;
- return oss.str();
- }
- };
- int main()
- {
- StringFormat sf("{1}+{0}={2}");
- sf.Format(1, 2, 1+2);
- cout << sf.getResult();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement