Advertisement
pochti_da

format.h

Mar 7th, 2021
512
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. template <class T>
  2. static void process(int depth, std::vector <std::pair <int, std::string>>&args, T&& t) {
  3.     std::stringstream stream;
  4.     stream << t;
  5.  
  6.     std::string arg = stream.str();
  7.     for (auto &i : args) {
  8.         if (i.first > depth)
  9.             throw std::runtime_error("invalid argument index");
  10.         else if (i.first == depth)
  11.             i.second = arg;
  12.     }
  13. }
  14.  
  15. template <class T, class... ArgvT>
  16. static void process(int depth, std::vector <std::pair <int, std::string>>& args, T&& t, ArgvT&&... argv) {
  17.     std::stringstream stream;
  18.     stream << t;
  19.  
  20.     std::string arg = stream.str();
  21.     for (auto &i : args)
  22.         if (i.first == depth)
  23.             i.second = arg;
  24.  
  25.     process(++depth, args, std::forward<ArgvT>(argv)...);
  26. }
  27.  
  28. static bool is_size_t(const std::string& str) {
  29.     for (auto i : str)
  30.         if (i < '0' || i > '9')
  31.             return false;
  32.     return true;
  33. }
  34.  
  35. template <class... ArgvT>
  36. std::string format(const std::string& f, ArgvT&&... argv) {
  37.     std::vector <std::pair <int, std::string>> args;
  38.  
  39.     for (int i = 0; i < f.size(); ++i) {
  40.         if (f[i] == '{') {
  41.             int j = i + 1;
  42.             for (; j < f.size(); ++j)
  43.                 if (f[j] == '}')
  44.                     break;
  45.  
  46.             if (j == f.size())
  47.                 throw std::runtime_error("invalid brackets use");
  48.  
  49.             std::string number = f.substr(i + 1, j - i - 1);
  50.             if (is_size_t(number))
  51.                 args.push_back(std::make_pair(std::stoi(number), ""));
  52.         }
  53.     }
  54.  
  55.     process(0, args, std::forward<ArgvT>(argv)...);
  56.  
  57.     std::string res = "";
  58.     int ind = 0;
  59.     for (int i = 0; i < f.size(); ++i) {
  60.         if (f[i] == '{') {
  61.             while (f[i] != '}')
  62.                 ++i;
  63.  
  64.             res += args[ind++].second;
  65.         }
  66.         else
  67.             res += f[i];
  68.     }
  69.  
  70.     return res;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement