Advertisement
Guest User

Untitled

a guest
Aug 24th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <cstdio>
  2. #include <sstream>
  3. #include <initializer_list>
  4.  
  5.  
  6. namespace Internal
  7. {
  8. // In real code those are declared `extern` and initialization is moved from .h into .cpp
  9. std::stringstream ss;
  10. const std::stringstream::fmtflags stdfmt = ss.flags();
  11. }
  12.  
  13. // Jo() resets stringstream flags before performing concatenation.
  14. // Jo_() does not.
  15.  
  16. template <typename ...P> const char *Jo_(P &&... p)
  17. {
  18. // Multiple buffers to allow use of multiple Jo()'s in a single expression.
  19. static constexpr int ret_buffers_c = 32;
  20. static std::string ret_buffers[ret_buffers_c];
  21. static int ret_pos = 0;
  22.  
  23. Internal::ss.clear(); // Clear the error flags.
  24. Internal::ss.str(""); // Clear stringstream contents.
  25.  
  26. // Push all objects to stringstream.
  27. std::initializer_list<int>{(Internal::ss << p, 0)...};
  28.  
  29. // Save to buffer and return a pointer.
  30. ret_buffers[ret_pos] = Internal::ss.str();
  31. const char *ret = ret_buffers[ret_pos].c_str();
  32. ret_pos = (ret_pos + 1) % ret_buffers_c;
  33. return ret;
  34. }
  35.  
  36. template <typename ...P> const char *Jo(P &&... p)
  37. {
  38. Internal::ss.flags(Internal::stdfmt);
  39. return Jo_((P &&) p...);
  40. }
  41.  
  42.  
  43. // Example usage:
  44. int main()
  45. {
  46. for (int i = 1; i <= 10; i++)
  47. std::puts(Jo(i, " * ", i+1, " = ", i*i+i));
  48. return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement