printf.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Boost.TypeErasure library
  2. //
  3. // Copyright 2012 Steven Watanabe
  4. //
  5. // Distributed under the Boost Software License Version 1.0. (See
  6. // accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // $Id$
  10. //[printf
  11. /*`
  12. (For the source of this example see
  13. [@boost:/libs/type_erasure/example/printf.cpp printf.cpp])
  14. This example uses the library to implement a type safe printf.
  15. [note This example uses C++11 features. You'll need a
  16. recent compiler for it to work.]
  17. */
  18. #include <boost/type_erasure/builtin.hpp>
  19. #include <boost/type_erasure/operators.hpp>
  20. #include <boost/type_erasure/any_cast.hpp>
  21. #include <boost/type_erasure/any.hpp>
  22. #include <boost/mpl/vector.hpp>
  23. #include <boost/io/ios_state.hpp>
  24. #include <iostream>
  25. #include <sstream>
  26. #include <iomanip>
  27. #include <vector>
  28. #include <string>
  29. namespace mpl = boost::mpl;
  30. using namespace boost::type_erasure;
  31. using namespace boost::io;
  32. // We capture the arguments by reference and require nothing
  33. // except that each one must provide a stream insertion operator.
  34. typedef any<
  35. mpl::vector<
  36. typeid_<>,
  37. ostreamable<>
  38. >,
  39. const _self&
  40. > any_printable;
  41. typedef std::vector<any_printable> print_storage;
  42. // Forward declaration of the implementation function
  43. void print_impl(std::ostream& os, const char * format, const print_storage& args);
  44. // print
  45. //
  46. // Writes values to a stream like the classic C printf function. The
  47. // arguments are formatted based on specifiers in the format string,
  48. // which match the pattern:
  49. //
  50. // '%' [ argument-number '$' ] flags * [ width ] [ '.' precision ] [ type-code ] format-specifier
  51. //
  52. // Other characters in the format string are written to the stream unchanged.
  53. // In addition the sequence, "%%" can be used to print a literal '%' character.
  54. // Each component is explained in detail below
  55. //
  56. // argument-number:
  57. // The value must be between 1 and sizeof... T. It indicates the
  58. // index of the argument to be formatted. If no index is specified
  59. // the arguments will be processed sequentially. If an index is
  60. // specified for one argument, then it must be specified for every argument.
  61. //
  62. // flags:
  63. // Consists of zero or more of the following:
  64. // '-': Left justify the argument
  65. // '+': Print a plus sign for positive integers
  66. // '0': Use leading 0's to pad instead of filling with spaces.
  67. // ' ': If the value doesn't begin with a sign, prepend a space
  68. // '#': Print 0x or 0 for hexadecimal and octal numbers.
  69. //
  70. // width:
  71. // Indicates the minimum width to print. This can be either
  72. // an integer or a '*'. an asterisk means to read the next
  73. // argument (which must have type int) as the width.
  74. //
  75. // precision:
  76. // For numeric arguments, indicates the number of digits to print. For
  77. // strings (%s) the precision indicates the maximum number of characters
  78. // to print. Longer strings will be truncated. As with width
  79. // this can be either an integer or a '*'. an asterisk means
  80. // to read the next argument (which must have type int) as
  81. // the width. If both the width and the precision are specified
  82. // as '*', the width is read first.
  83. //
  84. // type-code:
  85. // This is ignored, but provided for compatibility with C printf.
  86. //
  87. // format-specifier:
  88. // Must be one of the following characters:
  89. // d, i, u: The argument is formatted as a decimal integer
  90. // o: The argument is formatted as an octal integer
  91. // x, X: The argument is formatted as a hexadecimal integer
  92. // p: The argument is formatted as a pointer
  93. // f: The argument is formatted as a fixed point decimal
  94. // e, E: The argument is formatted in exponential notation
  95. // g, G: The argument is formatted as either fixed point or using
  96. // scientific notation depending on its magnitude
  97. // c: The argument is formatted as a character
  98. // s: The argument is formatted as a string
  99. //
  100. template<class... T>
  101. void print(std::ostream& os, const char * format, const T&... t)
  102. {
  103. // capture the arguments
  104. print_storage args = { any_printable(t)... };
  105. // and forward to the real implementation
  106. print_impl(os, format, args);
  107. }
  108. // This overload of print with no explicit stream writes to std::cout.
  109. template<class... T>
  110. void print(const char * format, const T&... t)
  111. {
  112. print(std::cout, format, t...);
  113. }
  114. // The implementation from here on can be separately compiled.
  115. // utility function to parse an integer
  116. int parse_int(const char *& format) {
  117. int result = 0;
  118. while(char ch = *format) {
  119. switch(ch) {
  120. case '0': case '1': case '2': case '3': case '4':
  121. case '5': case '6': case '7': case '8': case '9':
  122. result = result * 10 + (ch - '0');
  123. break;
  124. default: return result;
  125. }
  126. ++format;
  127. }
  128. return result;
  129. }
  130. // printf implementation
  131. void print_impl(std::ostream& os, const char * format, const print_storage& args) {
  132. int idx = 0;
  133. ios_flags_saver savef_outer(os, std::ios_base::dec);
  134. bool has_positional = false;
  135. bool has_indexed = false;
  136. while(char ch = *format++) {
  137. if (ch == '%') {
  138. if (*format == '%') { os << '%'; continue; }
  139. ios_flags_saver savef(os);
  140. ios_precision_saver savep(os);
  141. ios_fill_saver savefill(os);
  142. int precision = 0;
  143. bool pad_space = false;
  144. bool pad_zero = false;
  145. // parse argument index
  146. if (*format != '0') {
  147. int i = parse_int(format);
  148. if (i != 0) {
  149. if(*format == '$') {
  150. idx = i - 1;
  151. has_indexed = true;
  152. ++format;
  153. } else {
  154. os << std::setw(i);
  155. has_positional = true;
  156. goto parse_precision;
  157. }
  158. } else {
  159. has_positional = true;
  160. }
  161. } else {
  162. has_positional = true;
  163. }
  164. // Parse format modifiers
  165. while((ch = *format)) {
  166. switch(ch) {
  167. case '-': os << std::left; break;
  168. case '+': os << std::showpos; break;
  169. case '0': pad_zero = true; break;
  170. case ' ': pad_space = true; break;
  171. case '#': os << std::showpoint << std::showbase; break;
  172. default: goto parse_width;
  173. }
  174. ++format;
  175. }
  176. parse_width:
  177. int width;
  178. if (*format == '*') {
  179. ++format;
  180. width = any_cast<int>(args.at(idx++));
  181. } else {
  182. width = parse_int(format);
  183. }
  184. os << std::setw(width);
  185. parse_precision:
  186. if (*format == '.') {
  187. ++format;
  188. if (*format == '*') {
  189. ++format;
  190. precision = any_cast<int>(args.at(idx++));
  191. } else {
  192. precision = parse_int(format);
  193. }
  194. os << std::setprecision(precision);
  195. }
  196. // parse (and ignore) the type modifier
  197. switch(*format) {
  198. case 'h': ++format; if(*format == 'h') ++format; break;
  199. case 'l': ++format; if(*format == 'l') ++format; break;
  200. case 'j':
  201. case 'L':
  202. case 'q':
  203. case 't':
  204. case 'z':
  205. ++format; break;
  206. }
  207. std::size_t truncate = 0;
  208. // parse the format code
  209. switch(*format++) {
  210. case 'd': case 'i': case 'u': os << std::dec; break;
  211. case 'o': os << std::oct; break;
  212. case 'p': case 'x': os << std::hex; break;
  213. case 'X': os << std::uppercase << std::hex; break;
  214. case 'f': os << std::fixed; break;
  215. case 'e': os << std::scientific; break;
  216. case 'E': os << std::uppercase << std::scientific; break;
  217. case 'g': break;
  218. case 'G': os << std::uppercase; break;
  219. case 'c': case 'C': break;
  220. case 's': case 'S': truncate = precision; os << std::setprecision(6); break;
  221. default: assert(!"Bad format string");
  222. }
  223. if (pad_zero && !(os.flags() & std::ios_base::left)) {
  224. os << std::setfill('0') << std::internal;
  225. pad_space = false;
  226. }
  227. if (truncate != 0 || pad_space) {
  228. // These can't be handled by std::setw. Write to a stringstream and
  229. // pad/truncate manually.
  230. std::ostringstream oss;
  231. oss.copyfmt(os);
  232. oss << args.at(idx++);
  233. std::string data = oss.str();
  234. if (pad_space) {
  235. if (data.empty() || (data[0] != '+' && data[0] != '-' && data[0] != ' ')) {
  236. os << ' ';
  237. }
  238. }
  239. if (truncate != 0 && data.size() > truncate) {
  240. data.resize(truncate);
  241. }
  242. os << data;
  243. } else {
  244. os << args.at(idx++);
  245. }
  246. // we can't have both positional and indexed arguments in
  247. // the format string.
  248. assert(has_positional ^ has_indexed);
  249. } else {
  250. std::cout << ch;
  251. }
  252. }
  253. }
  254. int main() {
  255. print("int: %d\n", 10);
  256. print("int: %0#8X\n", 0xA56E);
  257. print("double: %g\n", 3.14159265358979323846);
  258. print("double: %f\n", 3.14159265358979323846);
  259. print("double: %+20.9e\n", 3.14159265358979323846);
  260. print("double: %0+20.9g\n", 3.14159265358979323846);
  261. print("double: %*.*g\n", 20, 5, 3.14159265358979323846);
  262. print("string: %.10s\n", "Hello World!");
  263. print("double: %2$*.*g int: %1$d\n", 10, 20, 5, 3.14159265358979323846);
  264. }
  265. //]