fork download
  1. #include <tuple>
  2. #include <string>
  3. #include <sstream>
  4. #include <type_traits>
  5.  
  6. template<bool I>
  7. using Bool = std::integral_constant<bool, I>;
  8.  
  9. template<typename T>
  10. using EnableIf = typename std::enable_if<T::value>::type;
  11.  
  12. namespace detail {
  13. template<size_t N = 0, class Elem, class Traits, typename... Args, EnableIf<Bool<(N >= sizeof...(Args))>>...>
  14. inline void helper(std::basic_ostream<Elem,Traits>& out, const size_t i, const std::tuple<Args...>& tup) {}
  15. template<size_t N = 0, class Elem, class Traits, typename... Args, EnableIf<Bool<(N < sizeof...(Args))>>...>
  16. inline void helper(std::basic_ostream<Elem,Traits>& out, const size_t i, const std::tuple<Args...>& tup) {
  17. if(i == N) {
  18. out << std::get<N>(tup);
  19. }
  20. else {
  21. helper<N+1, Elem, Traits, Args...>(out, i, tup);
  22. }
  23. }
  24. } // detail
  25.  
  26.  
  27. // {{{{{0},1 prints {{1
  28.  
  29. template<size_t N = 0, typename... Args>
  30. std::string format(const std::string& str, Args&&... args) {
  31. if(sizeof...(args) < 1)
  32. return str;
  33. auto tup = std::make_tuple(std::forward<Args>(args)...);
  34. auto first = std::begin(str);
  35. auto last = std::end(str);
  36. size_t index = 0;
  37. std::ostringstream out;
  38. while(first != last) {
  39. if(*first != '{') {
  40. out << *first++;
  41. continue;
  42. }
  43. else { // If it's a { character
  44. auto check = first;
  45. if(++check == last || *check == '}') {
  46. // Special cases.
  47. out << *first++;
  48. continue;
  49. }
  50. index = 0;
  51. // Keep incrementing the index.
  52. while(check != last && (*check >= '0' && *check <= '9')) {
  53. index *= 10;
  54. index += ((*check) - '0');
  55. ++check;
  56. }
  57. if(*check == '}') {
  58. detail::helper(out, index, tup);
  59. ++check;
  60. }
  61. else {
  62. out << *check;
  63. }
  64. first = check;
  65. }
  66. }
  67. std::string result = out.str();
  68. return result;
  69. }
  70.  
  71. #include <iostream>
  72.  
  73. int main() {
  74. std::cout << format("{{{{{0}",1) << '\n' << format("{{{{{0}{{",1) << '\n' << format("{{{{{0}{{}{}",1) << '\n';
  75. auto a = format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}", 1,2,3,4,5,6,7,8,9,10,11,12);
  76. auto b = format("{0} + {0} = {1}", 2, 4);
  77. std::cout << format(4 > 5 ? "({0})" : "[{0}]", 10) << '\n' << a << '\n' << b;
  78. }
  79.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
{{{{1
{{{{1{{
{{{{1{{}{}
[10]
1,2,3,4,5,6,7,8,9,10,11,12
2 + 2 = 4