You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tinyformat.h 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // tinyformat.h
  2. // Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com]
  3. //
  4. // Boost Software License - Version 1.0
  5. //
  6. // Permission is hereby granted, free of charge, to any person or organization
  7. // obtaining a copy of the software and accompanying documentation covered by
  8. // this license (the "Software") to use, reproduce, display, distribute,
  9. // execute, and transmit the Software, and to prepare derivative works of the
  10. // Software, and to permit third-parties to whom the Software is furnished to
  11. // do so, all subject to the following:
  12. //
  13. // The copyright notices in the Software and this entire statement, including
  14. // the above license grant, this restriction and the following disclaimer,
  15. // must be included in all copies of the Software, in whole or in part, and
  16. // all derivative works of the Software, unless such copies or derivative
  17. // works are solely in the form of machine-executable object code generated by
  18. // a source language processor.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  23. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  24. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  25. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  26. // DEALINGS IN THE SOFTWARE.
  27. //------------------------------------------------------------------------------
  28. // Tinyformat: A minimal type safe printf replacement
  29. //
  30. // tinyformat.h is a type safe printf replacement library in a single C++
  31. // header file. Design goals include:
  32. //
  33. // * Type safety and extensibility for user defined types.
  34. // * C99 printf() compatibility, to the extent possible using std::ostream
  35. // * Simplicity and minimalism. A single header file to include and distribute
  36. // with your projects.
  37. // * Augment rather than replace the standard stream formatting mechanism
  38. // * C++98 support, with optional C++11 niceties
  39. //
  40. //
  41. // Main interface example usage
  42. // ----------------------------
  43. //
  44. // To print a date to std::cout:
  45. //
  46. // std::string weekday = "Wednesday";
  47. // const char* month = "July";
  48. // size_t day = 27;
  49. // long hour = 14;
  50. // int min = 44;
  51. //
  52. // tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);
  53. //
  54. // The strange types here emphasize the type safety of the interface; it is
  55. // possible to print a std::string using the "%s" conversion, and a
  56. // size_t using the "%d" conversion. A similar result could be achieved
  57. // using either of the tfm::format() functions. One prints on a user provided
  58. // stream:
  59. //
  60. // tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",
  61. // weekday, month, day, hour, min);
  62. //
  63. // The other returns a std::string:
  64. //
  65. // std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",
  66. // weekday, month, day, hour, min);
  67. // std::cout << date;
  68. //
  69. // These are the three primary interface functions. There is also a
  70. // convenience function printfln() which appends a newline to the usual result
  71. // of printf() for super simple logging.
  72. //
  73. //
  74. // User defined format functions
  75. // -----------------------------
  76. //
  77. // Simulating variadic templates in C++98 is pretty painful since it requires
  78. // writing out the same function for each desired number of arguments. To make
  79. // this bearable tinyformat comes with a set of macros which are used
  80. // internally to generate the API, but which may also be used in user code.
  81. //
  82. // The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and
  83. // TINYFORMAT_PASSARGS(n) will generate a list of n argument types,
  84. // type/name pairs and argument names respectively when called with an integer
  85. // n between 1 and 16. We can use these to define a macro which generates the
  86. // desired user defined function with n arguments. To generate all 16 user
  87. // defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an
  88. // example, see the implementation of printf() at the end of the source file.
  89. //
  90. // Sometimes it's useful to be able to pass a list of format arguments through
  91. // to a non-template function. The FormatList class is provided as a way to do
  92. // this by storing the argument list in a type-opaque way. Continuing the
  93. // example from above, we construct a FormatList using makeFormatList():
  94. //
  95. // FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min);
  96. //
  97. // The format list can now be passed into any non-template function and used
  98. // via a call to the vformat() function:
  99. //
  100. // tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList);
  101. //
  102. //
  103. // Additional API information
  104. // --------------------------
  105. //
  106. // Error handling: Define TINYFORMAT_ERROR to customize the error handling for
  107. // format strings which are unsupported or have the wrong number of format
  108. // specifiers (calls assert() by default).
  109. //
  110. // User defined types: Uses operator<< for user defined types by default.
  111. // Overload formatValue() for more control.
  112. #ifndef TINYFORMAT_H_INCLUDED
  113. #define TINYFORMAT_H_INCLUDED
  114. namespace tinyformat {}
  115. //------------------------------------------------------------------------------
  116. // Config section. Customize to your liking!
  117. // Namespace alias to encourage brevity
  118. namespace tfm = tinyformat;
  119. // Error handling; calls assert() by default.
  120. #define TINYFORMAT_ERROR(reasonString) throw tinyformat::format_error(reasonString)
  121. // Define for C++11 variadic templates which make the code shorter & more
  122. // general. If you don't define this, C++11 support is autodetected below.
  123. #define TINYFORMAT_USE_VARIADIC_TEMPLATES
  124. //------------------------------------------------------------------------------
  125. // Implementation details.
  126. #include <algorithm>
  127. #include <cassert>
  128. #include <iostream>
  129. #include <sstream>
  130. #include <stdexcept>
  131. #ifndef TINYFORMAT_ERROR
  132. # define TINYFORMAT_ERROR(reason) assert(0 && reason)
  133. #endif
  134. #if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)
  135. # ifdef __GXX_EXPERIMENTAL_CXX0X__
  136. # define TINYFORMAT_USE_VARIADIC_TEMPLATES
  137. # endif
  138. #endif
  139. #if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201
  140. // std::showpos is broken on old libstdc++ as provided with OSX. See
  141. // http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html
  142. # define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
  143. #endif
  144. #ifdef __APPLE__
  145. // Workaround OSX linker warning: xcode uses different default symbol
  146. // visibilities for static libs vs executables (see issue #25)
  147. # define TINYFORMAT_HIDDEN __attribute__((visibility("hidden")))
  148. #else
  149. # define TINYFORMAT_HIDDEN
  150. #endif
  151. namespace tinyformat {
  152. class format_error: public std::runtime_error
  153. {
  154. public:
  155. format_error(const std::string &what): std::runtime_error(what) {
  156. }
  157. };
  158. //------------------------------------------------------------------------------
  159. namespace detail {
  160. // Test whether type T1 is convertible to type T2
  161. template <typename T1, typename T2>
  162. struct is_convertible
  163. {
  164. private:
  165. // two types of different size
  166. struct fail { char dummy[2]; };
  167. struct succeed { char dummy; };
  168. // Try to convert a T1 to a T2 by plugging into tryConvert
  169. static fail tryConvert(...);
  170. static succeed tryConvert(const T2&);
  171. static const T1& makeT1();
  172. public:
  173. # ifdef _MSC_VER
  174. // Disable spurious loss of precision warnings in tryConvert(makeT1())
  175. # pragma warning(push)
  176. # pragma warning(disable:4244)
  177. # pragma warning(disable:4267)
  178. # endif
  179. // Standard trick: the (...) version of tryConvert will be chosen from
  180. // the overload set only if the version taking a T2 doesn't match.
  181. // Then we compare the sizes of the return types to check which
  182. // function matched. Very neat, in a disgusting kind of way :)
  183. static const bool value =
  184. sizeof(tryConvert(makeT1())) == sizeof(succeed);
  185. # ifdef _MSC_VER
  186. # pragma warning(pop)
  187. # endif
  188. };
  189. // Detect when a type is not a wchar_t string
  190. template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };
  191. template<> struct is_wchar<wchar_t*> {};
  192. template<> struct is_wchar<const wchar_t*> {};
  193. template<int n> struct is_wchar<const wchar_t[n]> {};
  194. template<int n> struct is_wchar<wchar_t[n]> {};
  195. // Format the value by casting to type fmtT. This default implementation
  196. // should never be called.
  197. template<typename T, typename fmtT, bool convertible = is_convertible<T, fmtT>::value>
  198. struct formatValueAsType
  199. {
  200. static void invoke(std::ostream& /*out*/, const T& /*value*/) { assert(0); }
  201. };
  202. // Specialized version for types that can actually be converted to fmtT, as
  203. // indicated by the "convertible" template parameter.
  204. template<typename T, typename fmtT>
  205. struct formatValueAsType<T,fmtT,true>
  206. {
  207. static void invoke(std::ostream& out, const T& value)
  208. { out << static_cast<fmtT>(value); }
  209. };
  210. #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
  211. template<typename T, bool convertible = is_convertible<T, int>::value>
  212. struct formatZeroIntegerWorkaround
  213. {
  214. static bool invoke(std::ostream& /**/, const T& /**/) { return false; }
  215. };
  216. template<typename T>
  217. struct formatZeroIntegerWorkaround<T,true>
  218. {
  219. static bool invoke(std::ostream& out, const T& value)
  220. {
  221. if (static_cast<int>(value) == 0 && out.flags() & std::ios::showpos)
  222. {
  223. out << "+0";
  224. return true;
  225. }
  226. return false;
  227. }
  228. };
  229. #endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
  230. // Convert an arbitrary type to integer. The version with convertible=false
  231. // throws an error.
  232. template<typename T, bool convertible = is_convertible<T,int>::value>
  233. struct convertToInt
  234. {
  235. static int invoke(const T& /*value*/)
  236. {
  237. TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to "
  238. "integer for use as variable width or precision");
  239. return 0;
  240. }
  241. };
  242. // Specialization for convertToInt when conversion is possible
  243. template<typename T>
  244. struct convertToInt<T,true>
  245. {
  246. static int invoke(const T& value) { return static_cast<int>(value); }
  247. };
  248. // Format at most ntrunc characters to the given stream.
  249. template<typename T>
  250. inline void formatTruncated(std::ostream& out, const T& value, int ntrunc)
  251. {
  252. std::ostringstream tmp;
  253. tmp << value;
  254. std::string result = tmp.str();
  255. out.write(result.c_str(), (std::min)(ntrunc, static_cast<int>(result.size())));
  256. }
  257. #define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type) \
  258. inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \
  259. { \
  260. std::streamsize len = 0; \
  261. while(len < ntrunc && value[len] != 0) \
  262. ++len; \
  263. out.write(value, len); \
  264. }
  265. // Overload for const char* and char*. Could overload for signed & unsigned
  266. // char too, but these are technically unneeded for printf compatibility.
  267. TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char)
  268. TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char)
  269. #undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR
  270. } // namespace detail
  271. //------------------------------------------------------------------------------
  272. // Variable formatting functions. May be overridden for user-defined types if
  273. // desired.
  274. /// Format a value into a stream, delegating to operator<< by default.
  275. ///
  276. /// Users may override this for their own types. When this function is called,
  277. /// the stream flags will have been modified according to the format string.
  278. /// The format specification is provided in the range [fmtBegin, fmtEnd). For
  279. /// truncating conversions, ntrunc is set to the desired maximum number of
  280. /// characters, for example "%.7s" calls formatValue with ntrunc = 7.
  281. ///
  282. /// By default, formatValue() uses the usual stream insertion operator
  283. /// operator<< to format the type T, with special cases for the %c and %p
  284. /// conversions.
  285. template<typename T>
  286. inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,
  287. const char* fmtEnd, int ntrunc, const T& value)
  288. {
  289. #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS
  290. // Since we don't support printing of wchar_t using "%ls", make it fail at
  291. // compile time in preference to printing as a void* at runtime.
  292. typedef typename detail::is_wchar<T>::tinyformat_wchar_is_not_supported DummyType;
  293. (void) DummyType(); // avoid unused type warning with gcc-4.8
  294. #endif
  295. // The mess here is to support the %c and %p conversions: if these
  296. // conversions are active we try to convert the type to a char or const
  297. // void* respectively and format that instead of the value itself. For the
  298. // %p conversion it's important to avoid dereferencing the pointer, which
  299. // could otherwise lead to a crash when printing a dangling (const char*).
  300. const bool canConvertToChar = detail::is_convertible<T,char>::value;
  301. const bool canConvertToVoidPtr = detail::is_convertible<T, const void*>::value;
  302. if(canConvertToChar && *(fmtEnd-1) == 'c')
  303. detail::formatValueAsType<T, char>::invoke(out, value);
  304. else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p')
  305. detail::formatValueAsType<T, const void*>::invoke(out, value);
  306. #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
  307. else if(detail::formatZeroIntegerWorkaround<T>::invoke(out, value)) /**/;
  308. #endif
  309. else if(ntrunc >= 0)
  310. {
  311. // Take care not to overread C strings in truncating conversions like
  312. // "%.4s" where at most 4 characters may be read.
  313. detail::formatTruncated(out, value, ntrunc);
  314. }
  315. else
  316. out << value;
  317. }
  318. // Overloaded version for char types to support printing as an integer
  319. #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \
  320. inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \
  321. const char* fmtEnd, int /**/, charType value) \
  322. { \
  323. switch(*(fmtEnd-1)) \
  324. { \
  325. case 'u': case 'd': case 'i': case 'o': case 'X': case 'x': \
  326. out << static_cast<int>(value); break; \
  327. default: \
  328. out << value; break; \
  329. } \
  330. }
  331. // per 3.9.1: char, signed char and unsigned char are all distinct types
  332. TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char)
  333. TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char)
  334. TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char)
  335. #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR
  336. //------------------------------------------------------------------------------
  337. // Tools for emulating variadic templates in C++98. The basic idea here is
  338. // stolen from the boost preprocessor metaprogramming library and cut down to
  339. // be just general enough for what we need.
  340. #define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n
  341. #define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n
  342. #define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n
  343. #define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n
  344. // To keep it as transparent as possible, the macros below have been generated
  345. // using python via the excellent cog.py code generation script. This avoids
  346. // the need for a bunch of complex (but more general) preprocessor tricks as
  347. // used in boost.preprocessor.
  348. //
  349. // To rerun the code generation in place, use `cog.py -r tinyformat.h`
  350. // (see http://nedbatchelder.com/code/cog). Alternatively you can just create
  351. // extra versions by hand.
  352. /*[[[cog
  353. maxParams = 16
  354. def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1):
  355. for j in range(startInd,maxParams+1):
  356. list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)])
  357. cog.outl(lineTemplate % {'j':j, 'list':list})
  358. makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s',
  359. 'class T%(i)d')
  360. cog.outl()
  361. makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s',
  362. 'const T%(i)d& v%(i)d')
  363. cog.outl()
  364. makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d')
  365. cog.outl()
  366. cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1')
  367. makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s',
  368. 'v%(i)d', startInd = 2)
  369. cog.outl()
  370. cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' +
  371. ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)]))
  372. ]]]*/
  373. #define TINYFORMAT_ARGTYPES_1 class T1
  374. #define TINYFORMAT_ARGTYPES_2 class T1, class T2
  375. #define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3
  376. #define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4
  377. #define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5
  378. #define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6
  379. #define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7
  380. #define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8
  381. #define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9
  382. #define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10
  383. #define TINYFORMAT_ARGTYPES_11 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11
  384. #define TINYFORMAT_ARGTYPES_12 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12
  385. #define TINYFORMAT_ARGTYPES_13 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13
  386. #define TINYFORMAT_ARGTYPES_14 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14
  387. #define TINYFORMAT_ARGTYPES_15 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15
  388. #define TINYFORMAT_ARGTYPES_16 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16
  389. #define TINYFORMAT_VARARGS_1 const T1& v1
  390. #define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2
  391. #define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3
  392. #define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4
  393. #define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5
  394. #define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6
  395. #define TINYFORMAT_VARARGS_7 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7
  396. #define TINYFORMAT_VARARGS_8 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8
  397. #define TINYFORMAT_VARARGS_9 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9
  398. #define TINYFORMAT_VARARGS_10 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10
  399. #define TINYFORMAT_VARARGS_11 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11
  400. #define TINYFORMAT_VARARGS_12 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12
  401. #define TINYFORMAT_VARARGS_13 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13
  402. #define TINYFORMAT_VARARGS_14 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14
  403. #define TINYFORMAT_VARARGS_15 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15
  404. #define TINYFORMAT_VARARGS_16 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15, const T16& v16
  405. #define TINYFORMAT_PASSARGS_1 v1
  406. #define TINYFORMAT_PASSARGS_2 v1, v2
  407. #define TINYFORMAT_PASSARGS_3 v1, v2, v3
  408. #define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4
  409. #define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5
  410. #define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6
  411. #define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7
  412. #define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8
  413. #define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9
  414. #define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10
  415. #define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
  416. #define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
  417. #define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
  418. #define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
  419. #define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
  420. #define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
  421. #define TINYFORMAT_PASSARGS_TAIL_1
  422. #define TINYFORMAT_PASSARGS_TAIL_2 , v2
  423. #define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3
  424. #define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4
  425. #define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5
  426. #define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6
  427. #define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7
  428. #define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8
  429. #define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9
  430. #define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10
  431. #define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
  432. #define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
  433. #define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
  434. #define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
  435. #define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
  436. #define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
  437. #define TINYFORMAT_FOREACH_ARGNUM(m) \
  438. m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) m(15) m(16)
  439. //[[[end]]]
  440. namespace detail {
  441. // Type-opaque holder for an argument to format(), with associated actions on
  442. // the type held as explicit function pointers. This allows FormatArg's for
  443. // each argument to be allocated as a homogenous array inside FormatList
  444. // whereas a naive implementation based on inheritance does not.
  445. class FormatArg
  446. {
  447. public:
  448. FormatArg() {}
  449. template<typename T>
  450. FormatArg(const T& value)
  451. : m_value(static_cast<const void*>(&value)),
  452. m_formatImpl(&formatImpl<T>),
  453. m_toIntImpl(&toIntImpl<T>)
  454. { }
  455. void format(std::ostream& out, const char* fmtBegin,
  456. const char* fmtEnd, int ntrunc) const
  457. {
  458. m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value);
  459. }
  460. int toInt() const
  461. {
  462. return m_toIntImpl(m_value);
  463. }
  464. private:
  465. template<typename T>
  466. TINYFORMAT_HIDDEN static void formatImpl(std::ostream& out, const char* fmtBegin,
  467. const char* fmtEnd, int ntrunc, const void* value)
  468. {
  469. formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast<const T*>(value));
  470. }
  471. template<typename T>
  472. TINYFORMAT_HIDDEN static int toIntImpl(const void* value)
  473. {
  474. return convertToInt<T>::invoke(*static_cast<const T*>(value));
  475. }
  476. const void* m_value;
  477. void (*m_formatImpl)(std::ostream& out, const char* fmtBegin,
  478. const char* fmtEnd, int ntrunc, const void* value);
  479. int (*m_toIntImpl)(const void* value);
  480. };
  481. // Parse and return an integer from the string c, as atoi()
  482. // On return, c is set to one past the end of the integer.
  483. inline int parseIntAndAdvance(const char*& c)
  484. {
  485. int i = 0;
  486. for(;*c >= '0' && *c <= '9'; ++c)
  487. i = 10*i + (*c - '0');
  488. return i;
  489. }
  490. // Print literal part of format string and return next format spec
  491. // position.
  492. //
  493. // Skips over any occurrences of '%%', printing a literal '%' to the
  494. // output. The position of the first % character of the next
  495. // nontrivial format spec is returned, or the end of string.
  496. inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt)
  497. {
  498. const char* c = fmt;
  499. for(;; ++c)
  500. {
  501. switch(*c)
  502. {
  503. case '\0':
  504. out.write(fmt, c - fmt);
  505. return c;
  506. case '%':
  507. out.write(fmt, c - fmt);
  508. if(*(c+1) != '%')
  509. return c;
  510. // for "%%", tack trailing % onto next literal section.
  511. fmt = ++c;
  512. break;
  513. default:
  514. break;
  515. }
  516. }
  517. }
  518. // Parse a format string and set the stream state accordingly.
  519. //
  520. // The format mini-language recognized here is meant to be the one from C99,
  521. // with the form "%[flags][width][.precision][length]type".
  522. //
  523. // Formatting options which can't be natively represented using the ostream
  524. // state are returned in spacePadPositive (for space padded positive numbers)
  525. // and ntrunc (for truncating conversions). argIndex is incremented if
  526. // necessary to pull out variable width and precision . The function returns a
  527. // pointer to the character after the end of the current format spec.
  528. inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive,
  529. int& ntrunc, const char* fmtStart,
  530. const detail::FormatArg* formatters,
  531. int& argIndex, int numFormatters)
  532. {
  533. if(*fmtStart != '%')
  534. {
  535. TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string");
  536. return fmtStart;
  537. }
  538. // Reset stream state to defaults.
  539. out.width(0);
  540. out.precision(6);
  541. out.fill(' ');
  542. // Reset most flags; ignore irrelevant unitbuf & skipws.
  543. out.unsetf(std::ios::adjustfield | std::ios::basefield |
  544. std::ios::floatfield | std::ios::showbase | std::ios::boolalpha |
  545. std::ios::showpoint | std::ios::showpos | std::ios::uppercase);
  546. bool precisionSet = false;
  547. bool widthSet = false;
  548. int widthExtra = 0;
  549. const char* c = fmtStart + 1;
  550. // 1) Parse flags
  551. for(;; ++c)
  552. {
  553. switch(*c)
  554. {
  555. case '#':
  556. out.setf(std::ios::showpoint | std::ios::showbase);
  557. continue;
  558. case '0':
  559. // overridden by left alignment ('-' flag)
  560. if(!(out.flags() & std::ios::left))
  561. {
  562. // Use internal padding so that numeric values are
  563. // formatted correctly, eg -00010 rather than 000-10
  564. out.fill('0');
  565. out.setf(std::ios::internal, std::ios::adjustfield);
  566. }
  567. continue;
  568. case '-':
  569. out.fill(' ');
  570. out.setf(std::ios::left, std::ios::adjustfield);
  571. continue;
  572. case ' ':
  573. // overridden by show positive sign, '+' flag.
  574. if(!(out.flags() & std::ios::showpos))
  575. spacePadPositive = true;
  576. continue;
  577. case '+':
  578. out.setf(std::ios::showpos);
  579. spacePadPositive = false;
  580. widthExtra = 1;
  581. continue;
  582. default:
  583. break;
  584. }
  585. break;
  586. }
  587. // 2) Parse width
  588. if(*c >= '0' && *c <= '9')
  589. {
  590. widthSet = true;
  591. out.width(parseIntAndAdvance(c));
  592. }
  593. if(*c == '*')
  594. {
  595. widthSet = true;
  596. int width = 0;
  597. if(argIndex < numFormatters)
  598. width = formatters[argIndex++].toInt();
  599. else
  600. TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width");
  601. if(width < 0)
  602. {
  603. // negative widths correspond to '-' flag set
  604. out.fill(' ');
  605. out.setf(std::ios::left, std::ios::adjustfield);
  606. width = -width;
  607. }
  608. out.width(width);
  609. ++c;
  610. }
  611. // 3) Parse precision
  612. if(*c == '.')
  613. {
  614. ++c;
  615. int precision = 0;
  616. if(*c == '*')
  617. {
  618. ++c;
  619. if(argIndex < numFormatters)
  620. precision = formatters[argIndex++].toInt();
  621. else
  622. TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable precision");
  623. }
  624. else
  625. {
  626. if(*c >= '0' && *c <= '9')
  627. precision = parseIntAndAdvance(c);
  628. else if(*c == '-') // negative precisions ignored, treated as zero.
  629. parseIntAndAdvance(++c);
  630. }
  631. out.precision(precision);
  632. precisionSet = true;
  633. }
  634. // 4) Ignore any C99 length modifier
  635. while(*c == 'l' || *c == 'h' || *c == 'L' ||
  636. *c == 'j' || *c == 'z' || *c == 't')
  637. ++c;
  638. // 5) We're up to the conversion specifier character.
  639. // Set stream flags based on conversion specifier (thanks to the
  640. // boost::format class for forging the way here).
  641. bool intConversion = false;
  642. switch(*c)
  643. {
  644. case 'u': case 'd': case 'i':
  645. out.setf(std::ios::dec, std::ios::basefield);
  646. intConversion = true;
  647. break;
  648. case 'o':
  649. out.setf(std::ios::oct, std::ios::basefield);
  650. intConversion = true;
  651. break;
  652. case 'X':
  653. out.setf(std::ios::uppercase);
  654. case 'x': case 'p':
  655. out.setf(std::ios::hex, std::ios::basefield);
  656. intConversion = true;
  657. break;
  658. case 'E':
  659. out.setf(std::ios::uppercase);
  660. case 'e':
  661. out.setf(std::ios::scientific, std::ios::floatfield);
  662. out.setf(std::ios::dec, std::ios::basefield);
  663. break;
  664. case 'F':
  665. out.setf(std::ios::uppercase);
  666. case 'f':
  667. out.setf(std::ios::fixed, std::ios::floatfield);
  668. break;
  669. case 'G':
  670. out.setf(std::ios::uppercase);
  671. case 'g':
  672. out.setf(std::ios::dec, std::ios::basefield);
  673. // As in boost::format, let stream decide float format.
  674. out.flags(out.flags() & ~std::ios::floatfield);
  675. break;
  676. case 'a': case 'A':
  677. TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs "
  678. "are not supported");
  679. break;
  680. case 'c':
  681. // Handled as special case inside formatValue()
  682. break;
  683. case 's':
  684. if(precisionSet)
  685. ntrunc = static_cast<int>(out.precision());
  686. // Make %s print booleans as "true" and "false"
  687. out.setf(std::ios::boolalpha);
  688. break;
  689. case 'n':
  690. // Not supported - will cause problems!
  691. TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported");
  692. break;
  693. case '\0':
  694. TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly "
  695. "terminated by end of string");
  696. return c;
  697. default:
  698. break;
  699. }
  700. if(intConversion && precisionSet && !widthSet)
  701. {
  702. // "precision" for integers gives the minimum number of digits (to be
  703. // padded with zeros on the left). This isn't really supported by the
  704. // iostreams, but we can approximately simulate it with the width if
  705. // the width isn't otherwise used.
  706. out.width(out.precision() + widthExtra);
  707. out.setf(std::ios::internal, std::ios::adjustfield);
  708. out.fill('0');
  709. }
  710. return c+1;
  711. }
  712. //------------------------------------------------------------------------------
  713. inline void formatImpl(std::ostream& out, const char* fmt,
  714. const detail::FormatArg* formatters,
  715. int numFormatters)
  716. {
  717. // Saved stream state
  718. std::streamsize origWidth = out.width();
  719. std::streamsize origPrecision = out.precision();
  720. std::ios::fmtflags origFlags = out.flags();
  721. char origFill = out.fill();
  722. for (int argIndex = 0; argIndex < numFormatters; ++argIndex)
  723. {
  724. // Parse the format string
  725. fmt = printFormatStringLiteral(out, fmt);
  726. bool spacePadPositive = false;
  727. int ntrunc = -1;
  728. const char* fmtEnd = streamStateFromFormat(out, spacePadPositive, ntrunc, fmt,
  729. formatters, argIndex, numFormatters);
  730. if (argIndex >= numFormatters)
  731. {
  732. // Check args remain after reading any variable width/precision
  733. TINYFORMAT_ERROR("tinyformat: Not enough format arguments");
  734. return;
  735. }
  736. const FormatArg& arg = formatters[argIndex];
  737. // Format the arg into the stream.
  738. if(!spacePadPositive)
  739. arg.format(out, fmt, fmtEnd, ntrunc);
  740. else
  741. {
  742. // The following is a special case with no direct correspondence
  743. // between stream formatting and the printf() behaviour. Simulate
  744. // it crudely by formatting into a temporary string stream and
  745. // munging the resulting string.
  746. std::ostringstream tmpStream;
  747. tmpStream.copyfmt(out);
  748. tmpStream.setf(std::ios::showpos);
  749. arg.format(tmpStream, fmt, fmtEnd, ntrunc);
  750. std::string result = tmpStream.str(); // allocates... yuck.
  751. for(size_t i = 0, iend = result.size(); i < iend; ++i)
  752. if(result[i] == '+') result[i] = ' ';
  753. out << result;
  754. }
  755. fmt = fmtEnd;
  756. }
  757. // Print remaining part of format string.
  758. fmt = printFormatStringLiteral(out, fmt);
  759. if(*fmt != '\0')
  760. TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string");
  761. // Restore stream state
  762. out.width(origWidth);
  763. out.precision(origPrecision);
  764. out.flags(origFlags);
  765. out.fill(origFill);
  766. }
  767. } // namespace detail
  768. /// List of template arguments format(), held in a type-opaque way.
  769. ///
  770. /// A const reference to FormatList (typedef'd as FormatListRef) may be
  771. /// conveniently used to pass arguments to non-template functions: All type
  772. /// information has been stripped from the arguments, leaving just enough of a
  773. /// common interface to perform formatting as required.
  774. class FormatList
  775. {
  776. public:
  777. FormatList(detail::FormatArg* formatters, int N)
  778. : m_formatters(formatters), m_N(N) { }
  779. friend void vformat(std::ostream& out, const char* fmt,
  780. const FormatList& list);
  781. private:
  782. const detail::FormatArg* m_formatters;
  783. int m_N;
  784. };
  785. /// Reference to type-opaque format list for passing to vformat()
  786. typedef const FormatList& FormatListRef;
  787. namespace detail {
  788. // Format list subclass with fixed storage to avoid dynamic allocation
  789. template<int N>
  790. class FormatListN : public FormatList
  791. {
  792. public:
  793. #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
  794. template<typename... Args>
  795. FormatListN(const Args&... args)
  796. : FormatList(&m_formatterStore[0], N),
  797. m_formatterStore { FormatArg(args)... }
  798. { static_assert(sizeof...(args) == N, "Number of args must be N"); }
  799. #else // C++98 version
  800. void init(int) {}
  801. # define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n) \
  802. \
  803. template<TINYFORMAT_ARGTYPES(n)> \
  804. FormatListN(TINYFORMAT_VARARGS(n)) \
  805. : FormatList(&m_formatterStore[0], n) \
  806. { assert(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \
  807. \
  808. template<TINYFORMAT_ARGTYPES(n)> \
  809. void init(int i, TINYFORMAT_VARARGS(n)) \
  810. { \
  811. m_formatterStore[i] = FormatArg(v1); \
  812. init(i+1 TINYFORMAT_PASSARGS_TAIL(n)); \
  813. }
  814. TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR)
  815. # undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR
  816. #endif
  817. private:
  818. FormatArg m_formatterStore[N];
  819. };
  820. // Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard
  821. template<> class FormatListN<0> : public FormatList
  822. {
  823. public: FormatListN() : FormatList(0, 0) {}
  824. };
  825. } // namespace detail
  826. //------------------------------------------------------------------------------
  827. // Primary API functions
  828. #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
  829. /// Make type-agnostic format list from list of template arguments.
  830. ///
  831. /// The exact return type of this function is an implementation detail and
  832. /// shouldn't be relied upon. Instead it should be stored as a FormatListRef:
  833. ///
  834. /// FormatListRef formatList = makeFormatList( /*...*/ );
  835. template<typename... Args>
  836. detail::FormatListN<sizeof...(Args)> makeFormatList(const Args&... args)
  837. {
  838. return detail::FormatListN<sizeof...(args)>(args...);
  839. }
  840. #else // C++98 version
  841. inline detail::FormatListN<0> makeFormatList()
  842. {
  843. return detail::FormatListN<0>();
  844. }
  845. #define TINYFORMAT_MAKE_MAKEFORMATLIST(n) \
  846. template<TINYFORMAT_ARGTYPES(n)> \
  847. detail::FormatListN<n> makeFormatList(TINYFORMAT_VARARGS(n)) \
  848. { \
  849. return detail::FormatListN<n>(TINYFORMAT_PASSARGS(n)); \
  850. }
  851. TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST)
  852. #undef TINYFORMAT_MAKE_MAKEFORMATLIST
  853. #endif
  854. /// Format list of arguments to the stream according to the given format string.
  855. ///
  856. /// The name vformat() is chosen for the semantic similarity to vprintf(): the
  857. /// list of format arguments is held in a single function argument.
  858. inline void vformat(std::ostream& out, const char* fmt, FormatListRef list)
  859. {
  860. detail::formatImpl(out, fmt, list.m_formatters, list.m_N);
  861. }
  862. #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
  863. /// Format list of arguments to the stream according to given format string.
  864. template<typename... Args>
  865. void format(std::ostream& out, const char* fmt, const Args&... args)
  866. {
  867. vformat(out, fmt, makeFormatList(args...));
  868. }
  869. /// Format list of arguments according to the given format string and return
  870. /// the result as a string.
  871. template<typename... Args>
  872. std::string format(const char* fmt, const Args&... args)
  873. {
  874. std::ostringstream oss;
  875. format(oss, fmt, args...);
  876. return oss.str();
  877. }
  878. /// Format list of arguments to std::cout, according to the given format string
  879. template<typename... Args>
  880. void printf(const char* fmt, const Args&... args)
  881. {
  882. format(std::cout, fmt, args...);
  883. }
  884. template<typename... Args>
  885. void printfln(const char* fmt, const Args&... args)
  886. {
  887. format(std::cout, fmt, args...);
  888. std::cout << '\n';
  889. }
  890. #else // C++98 version
  891. inline void format(std::ostream& out, const char* fmt)
  892. {
  893. vformat(out, fmt, makeFormatList());
  894. }
  895. inline std::string format(const char* fmt)
  896. {
  897. std::ostringstream oss;
  898. format(oss, fmt);
  899. return oss.str();
  900. }
  901. inline void printf(const char* fmt)
  902. {
  903. format(std::cout, fmt);
  904. }
  905. inline void printfln(const char* fmt)
  906. {
  907. format(std::cout, fmt);
  908. std::cout << '\n';
  909. }
  910. #define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \
  911. \
  912. template<TINYFORMAT_ARGTYPES(n)> \
  913. void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \
  914. { \
  915. vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n))); \
  916. } \
  917. \
  918. template<TINYFORMAT_ARGTYPES(n)> \
  919. std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \
  920. { \
  921. std::ostringstream oss; \
  922. format(oss, fmt, TINYFORMAT_PASSARGS(n)); \
  923. return oss.str(); \
  924. } \
  925. \
  926. template<TINYFORMAT_ARGTYPES(n)> \
  927. void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \
  928. { \
  929. format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \
  930. } \
  931. \
  932. template<TINYFORMAT_ARGTYPES(n)> \
  933. void printfln(const char* fmt, TINYFORMAT_VARARGS(n)) \
  934. { \
  935. format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \
  936. std::cout << '\n'; \
  937. }
  938. TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS)
  939. #undef TINYFORMAT_MAKE_FORMAT_FUNCS
  940. #endif
  941. // Added for Starwels
  942. template<typename... Args>
  943. std::string format(const std::string &fmt, const Args&... args)
  944. {
  945. std::ostringstream oss;
  946. format(oss, fmt.c_str(), args...);
  947. return oss.str();
  948. }
  949. } // namespace tinyformat
  950. #define strprintf tfm::format
  951. #endif // TINYFORMAT_H_INCLUDED