Advertisement
Rochet2

c++ typeless format

Sep 29th, 2015
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <string>
  2. #include <sstream>
  3.  
  4. void format(std::ostringstream& ss, const char* fmt)
  5. {
  6.     if (!fmt || *fmt == '\0')
  7.     {
  8.         return;
  9.     }
  10.     while (*fmt != '\0')
  11.     {
  12.         if (*fmt == '%')
  13.         {
  14.             ++fmt;
  15.             if (*fmt == '?')
  16.             {
  17.                 ++fmt;
  18.                 ss << '?';
  19.                 break;
  20.             }
  21.             else if (*fmt != '%')
  22.                 continue;
  23.         }
  24.         ss << *fmt;
  25.         ++fmt;
  26.     }
  27. }
  28.  
  29. template <typename H, typename... T>
  30. void format(std::ostringstream& ss, const char* fmt, H&& p, T&&... t)
  31. {
  32.     if (!fmt || *fmt == '\0')
  33.     {
  34.         return;
  35.     }
  36.     while (*fmt != '\0')
  37.     {
  38.         if (*fmt == '%')
  39.         {
  40.             ++fmt;
  41.             if (*fmt == '?')
  42.             {
  43.                 ++fmt;
  44.                 ss << std::forward<H>(p);
  45.                 break;
  46.             }
  47.             else if (*fmt != '%')
  48.                 continue;
  49.         }
  50.         ss << *fmt;
  51.         ++fmt;
  52.     }
  53.     format(ss, fmt, std::forward<T>(t)...);
  54. }
  55.  
  56. template <typename... T>
  57. std::string format(const char* fmt, T... t)
  58. {
  59.     std::ostringstream oss;
  60.     format(oss, fmt, std::forward<T>(t)...);
  61.     return oss.str();
  62. }
  63.  
  64. #include <iostream> // for std::cout
  65.  
  66. int main()
  67. {
  68.     {
  69.         unsigned long long u = -1;
  70.         long long i = -1;
  71.         char c = 100;
  72.         std::cout << format("asd %? %? %? % %%", i, u, c) << std::endl;
  73.         return 0;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement