api.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. .. _string-formatting-api:
  2. *************
  3. API Reference
  4. *************
  5. The {fmt} library API consists of the following parts:
  6. * :ref:`fmt/core.h <core-api>`: the core API providing main formatting functions
  7. for ``char``/UTF-8 with C++20 compile-time checks and minimal dependencies
  8. * :ref:`fmt/format.h <format-api>`: the full format API providing additional
  9. formatting functions and locale support
  10. * :ref:`fmt/ranges.h <ranges-api>`: formatting of ranges and tuples
  11. * :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
  12. * :ref:`fmt/std.h <std-api>`: formatters for standard library types
  13. * :ref:`fmt/compile.h <compile-api>`: format string compilation
  14. * :ref:`fmt/color.h <color-api>`: terminal color and text style
  15. * :ref:`fmt/os.h <os-api>`: system APIs
  16. * :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
  17. * :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
  18. * :ref:`fmt/xchar.h <xchar-api>`: optional ``wchar_t`` support
  19. All functions and types provided by the library reside in namespace ``fmt`` and
  20. macros have prefix ``FMT_``.
  21. .. _core-api:
  22. Core API
  23. ========
  24. ``fmt/core.h`` defines the core API which provides main formatting functions
  25. for ``char``/UTF-8 with C++20 compile-time checks. It has minimal include
  26. dependencies for better compile times. This header is only beneficial when
  27. using {fmt} as a library and not in the header-only mode.
  28. The following functions use :ref:`format string syntax <syntax>`
  29. similar to that of Python's `str.format
  30. <https://docs.python.org/3/library/stdtypes.html#str.format>`_.
  31. They take *fmt* and *args* as arguments.
  32. *fmt* is a format string that contains literal text and replacement fields
  33. surrounded by braces ``{}``. The fields are replaced with formatted arguments
  34. in the resulting string. `~fmt::format_string` is a format string which can be
  35. implicitly constructed from a string literal or a ``constexpr`` string and is
  36. checked at compile time in C++20. To pass a runtime format string wrap it in
  37. `fmt::runtime`.
  38. *args* is an argument list representing objects to be formatted.
  39. .. _format:
  40. .. doxygenfunction:: format(format_string<T...> fmt, T&&... args) -> std::string
  41. .. doxygenfunction:: vformat(string_view fmt, format_args args) -> std::string
  42. .. doxygenfunction:: format_to(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt
  43. .. doxygenfunction:: format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -> format_to_n_result<OutputIt>
  44. .. doxygenfunction:: formatted_size(format_string<T...> fmt, T&&... args) -> size_t
  45. .. doxygenstruct:: fmt::format_to_n_result
  46. :members:
  47. .. _print:
  48. .. doxygenfunction:: fmt::print(format_string<T...> fmt, T&&... args)
  49. .. doxygenfunction:: fmt::vprint(string_view fmt, format_args args)
  50. .. doxygenfunction:: print(std::FILE *f, format_string<T...> fmt, T&&... args)
  51. .. doxygenfunction:: vprint(std::FILE *f, string_view fmt, format_args args)
  52. Compile-Time Format String Checks
  53. ---------------------------------
  54. Compile-time checks are enabled by default on compilers that support C++20
  55. ``consteval``. On older compilers you can use the ``FMT_STRING`` macro defined
  56. in ``fmt/format.h`` instead. It requires C++14 and is a no-op in C++11.
  57. .. doxygendefine:: FMT_STRING
  58. To force the use of legacy compile-time checks, define the preprocessor variable
  59. ``FMT_ENFORCE_COMPILE_STRING``. When set, functions accepting ``FMT_STRING``
  60. will fail to compile with regular strings. Runtime-checked formatting is still
  61. possible using ``fmt::vformat``, ``fmt::vprint``, etc.
  62. .. doxygenclass:: fmt::basic_format_string
  63. :members:
  64. .. doxygentypedef:: fmt::format_string
  65. .. doxygenfunction:: fmt::runtime(string_view) -> basic_runtime<char>
  66. Named Arguments
  67. ---------------
  68. .. doxygenfunction:: fmt::arg(const S&, const T&)
  69. Named arguments are not supported in compile-time checks at the moment.
  70. Argument Lists
  71. --------------
  72. You can create your own formatting function with compile-time checks and small
  73. binary footprint, for example (https://godbolt.org/z/oba4Mc):
  74. .. code:: c++
  75. #include <fmt/format.h>
  76. void vlog(const char* file, int line, fmt::string_view format,
  77. fmt::format_args args) {
  78. fmt::print("{}: {}: ", file, line);
  79. fmt::vprint(format, args);
  80. }
  81. template <typename S, typename... Args>
  82. void log(const char* file, int line, const S& format, Args&&... args) {
  83. vlog(file, line, format, fmt::make_format_args(args...));
  84. }
  85. #define MY_LOG(format, ...) \
  86. log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)
  87. MY_LOG("invalid squishiness: {}", 42);
  88. Note that ``vlog`` is not parameterized on argument types which improves compile
  89. times and reduces binary code size compared to a fully parameterized version.
  90. .. doxygenfunction:: fmt::make_format_args(const Args&...)
  91. .. doxygenclass:: fmt::format_arg_store
  92. :members:
  93. .. doxygenclass:: fmt::dynamic_format_arg_store
  94. :members:
  95. .. doxygenclass:: fmt::basic_format_args
  96. :members:
  97. .. doxygentypedef:: fmt::format_args
  98. .. doxygenclass:: fmt::basic_format_arg
  99. :members:
  100. .. doxygenclass:: fmt::basic_format_parse_context
  101. :members:
  102. .. doxygenclass:: fmt::basic_format_context
  103. :members:
  104. .. doxygentypedef:: fmt::format_context
  105. Compatibility
  106. -------------
  107. .. doxygenclass:: fmt::basic_string_view
  108. :members:
  109. .. doxygentypedef:: fmt::string_view
  110. Locale
  111. ------
  112. All formatting is locale-independent by default. Use the ``'L'`` format
  113. specifier to insert the appropriate number separator characters from the
  114. locale::
  115. #include <fmt/core.h>
  116. #include <locale>
  117. std::locale::global(std::locale("en_US.UTF-8"));
  118. auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
  119. .. _format-api:
  120. Format API
  121. ==========
  122. ``fmt/format.h`` defines the full format API providing additional formatting
  123. functions and locale support.
  124. .. _udt:
  125. Formatting User-Defined Types
  126. -----------------------------
  127. The {fmt} library provides formatters for many standard C++ types.
  128. See :ref:`fmt/ranges.h <ranges-api>` for ranges and tuples including standard
  129. containers such as ``std::vector``, :ref:`fmt/chrono.h <chrono-api>` for date
  130. and time formatting and :ref:`fmt/std.h <std-api>` for path and variant
  131. formatting.
  132. To make a user-defined type formattable, specialize the ``formatter<T>`` struct
  133. template and implement ``parse`` and ``format`` methods::
  134. #include <fmt/format.h>
  135. struct point {
  136. double x, y;
  137. };
  138. template <> struct fmt::formatter<point> {
  139. // Presentation format: 'f' - fixed, 'e' - exponential.
  140. char presentation = 'f';
  141. // Parses format specifications of the form ['f' | 'e'].
  142. constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
  143. // [ctx.begin(), ctx.end()) is a character range that contains a part of
  144. // the format string starting from the format specifications to be parsed,
  145. // e.g. in
  146. //
  147. // fmt::format("{:f} - point of interest", point{1, 2});
  148. //
  149. // the range will contain "f} - point of interest". The formatter should
  150. // parse specifiers until '}' or the end of the range. In this example
  151. // the formatter should parse the 'f' specifier and return an iterator
  152. // pointing to '}'.
  153. // Please also note that this character range may be empty, in case of
  154. // the "{}" format string, so therefore you should check ctx.begin()
  155. // for equality with ctx.end().
  156. // Parse the presentation format and store it in the formatter:
  157. auto it = ctx.begin(), end = ctx.end();
  158. if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
  159. // Check if reached the end of the range:
  160. if (it != end && *it != '}') throw format_error("invalid format");
  161. // Return an iterator past the end of the parsed range:
  162. return it;
  163. }
  164. // Formats the point p using the parsed format specification (presentation)
  165. // stored in this formatter.
  166. template <typename FormatContext>
  167. auto format(const point& p, FormatContext& ctx) const -> decltype(ctx.out()) {
  168. // ctx.out() is an output iterator to write to.
  169. return presentation == 'f'
  170. ? fmt::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y)
  171. : fmt::format_to(ctx.out(), "({:.1e}, {:.1e})", p.x, p.y);
  172. }
  173. };
  174. Then you can pass objects of type ``point`` to any formatting function::
  175. point p = {1, 2};
  176. std::string s = fmt::format("{:f}", p);
  177. // s == "(1.0, 2.0)"
  178. You can also reuse existing formatters via inheritance or composition, for
  179. example::
  180. enum class color {red, green, blue};
  181. template <> struct fmt::formatter<color>: formatter<string_view> {
  182. // parse is inherited from formatter<string_view>.
  183. template <typename FormatContext>
  184. auto format(color c, FormatContext& ctx) const {
  185. string_view name = "unknown";
  186. switch (c) {
  187. case color::red: name = "red"; break;
  188. case color::green: name = "green"; break;
  189. case color::blue: name = "blue"; break;
  190. }
  191. return formatter<string_view>::format(name, ctx);
  192. }
  193. };
  194. Since ``parse`` is inherited from ``formatter<string_view>`` it will recognize
  195. all string format specifications, for example
  196. .. code-block:: c++
  197. fmt::format("{:>10}", color::blue)
  198. will return ``" blue"``.
  199. You can also write a formatter for a hierarchy of classes::
  200. #include <type_traits>
  201. #include <fmt/format.h>
  202. struct A {
  203. virtual ~A() {}
  204. virtual std::string name() const { return "A"; }
  205. };
  206. struct B : A {
  207. virtual std::string name() const { return "B"; }
  208. };
  209. template <typename T>
  210. struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
  211. fmt::formatter<std::string> {
  212. template <typename FormatCtx>
  213. auto format(const A& a, FormatCtx& ctx) const {
  214. return fmt::formatter<std::string>::format(a.name(), ctx);
  215. }
  216. };
  217. int main() {
  218. B b;
  219. A& a = b;
  220. fmt::print("{}", a); // prints "B"
  221. }
  222. If a type provides both a ``formatter`` specialization and an implicit
  223. conversion to a formattable type, the specialization takes precedence over the
  224. conversion.
  225. For enums {fmt} also provides the ``format_as`` extension API. To format an enum
  226. via this API define ``format_as`` that takes this enum and converts it to the
  227. underlying type. ``format_as`` should be defined in the same namespace as the
  228. enum.
  229. Example (https://godbolt.org/z/r7vvGE1v7)::
  230. #include <fmt/format.h>
  231. namespace kevin_namespacy {
  232. enum class film {
  233. house_of_cards, american_beauty, se7en = 7
  234. };
  235. auto format_as(film f) { return fmt::underlying(f); }
  236. }
  237. int main() {
  238. fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7"
  239. }
  240. Literal-Based API
  241. -----------------
  242. The following user-defined literals are defined in ``fmt/format.h``.
  243. .. doxygenfunction:: operator""_a()
  244. Utilities
  245. ---------
  246. .. doxygenfunction:: fmt::ptr(T p) -> const void*
  247. .. doxygenfunction:: fmt::ptr(const std::unique_ptr<T> &p) -> const void*
  248. .. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p) -> const void*
  249. .. doxygenfunction:: fmt::underlying(Enum e) -> typename std::underlying_type<Enum>::type
  250. .. doxygenfunction:: fmt::to_string(const T &value) -> std::string
  251. .. doxygenfunction:: fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>
  252. .. doxygenfunction:: fmt::join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>
  253. .. doxygenfunction:: fmt::group_digits(T value) -> group_digits_view<T>
  254. .. doxygenclass:: fmt::detail::buffer
  255. :members:
  256. .. doxygenclass:: fmt::basic_memory_buffer
  257. :protected-members:
  258. :members:
  259. System Errors
  260. -------------
  261. {fmt} does not use ``errno`` to communicate errors to the user, but it may call
  262. system functions which set ``errno``. Users should not make any assumptions
  263. about the value of ``errno`` being preserved by library functions.
  264. .. doxygenfunction:: fmt::system_error
  265. .. doxygenfunction:: fmt::format_system_error
  266. Custom Allocators
  267. -----------------
  268. The {fmt} library supports custom dynamic memory allocators.
  269. A custom allocator class can be specified as a template argument to
  270. :class:`fmt::basic_memory_buffer`::
  271. using custom_memory_buffer =
  272. fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
  273. It is also possible to write a formatting function that uses a custom
  274. allocator::
  275. using custom_string =
  276. std::basic_string<char, std::char_traits<char>, custom_allocator>;
  277. custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
  278. fmt::format_args args) {
  279. auto buf = custom_memory_buffer(alloc);
  280. fmt::vformat_to(std::back_inserter(buf), format_str, args);
  281. return custom_string(buf.data(), buf.size(), alloc);
  282. }
  283. template <typename ...Args>
  284. inline custom_string format(custom_allocator alloc,
  285. fmt::string_view format_str,
  286. const Args& ... args) {
  287. return vformat(alloc, format_str, fmt::make_format_args(args...));
  288. }
  289. The allocator will be used for the output container only. Formatting functions
  290. normally don't do any allocations for built-in and string types except for
  291. non-default floating-point formatting that occasionally falls back on
  292. ``sprintf``.
  293. .. _ranges-api:
  294. Range and Tuple Formatting
  295. ==========================
  296. The library also supports convenient formatting of ranges and tuples::
  297. #include <fmt/ranges.h>
  298. std::tuple<char, int, float> t{'a', 1, 2.0f};
  299. // Prints "('a', 1, 2.0)"
  300. fmt::print("{}", t);
  301. NOTE: currently, the overload of ``fmt::join`` for iterables exists in the main
  302. ``format.h`` header, but expect this to change in the future.
  303. Using ``fmt::join``, you can separate tuple elements with a custom separator::
  304. #include <fmt/ranges.h>
  305. std::tuple<int, char> t = {1, 'a'};
  306. // Prints "1, a"
  307. fmt::print("{}", fmt::join(t, ", "));
  308. .. _chrono-api:
  309. Date and Time Formatting
  310. ========================
  311. ``fmt/chrono.h`` provides formatters for
  312. * `std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
  313. * `std::chrono::time_point
  314. <https://en.cppreference.com/w/cpp/chrono/time_point>`_
  315. * `std::tm <https://en.cppreference.com/w/cpp/chrono/c/tm>`_
  316. The format syntax is described in :ref:`chrono-specs`.
  317. **Example**::
  318. #include <fmt/chrono.h>
  319. int main() {
  320. std::time_t t = std::time(nullptr);
  321. // Prints "The date is 2020-11-07." (with the current date):
  322. fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
  323. using namespace std::literals::chrono_literals;
  324. // Prints "Default format: 42s 100ms":
  325. fmt::print("Default format: {} {}\n", 42s, 100ms);
  326. // Prints "strftime-like format: 03:15:30":
  327. fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
  328. }
  329. .. doxygenfunction:: localtime(std::time_t time)
  330. .. doxygenfunction:: gmtime(std::time_t time)
  331. .. _std-api:
  332. Standard Library Types Formatting
  333. =================================
  334. ``fmt/std.h`` provides formatters for:
  335. * `std::filesystem::path <https://en.cppreference.com/w/cpp/filesystem/path>`_
  336. * `std::thread::id <https://en.cppreference.com/w/cpp/thread/thread/id>`_
  337. * `std::monostate <https://en.cppreference.com/w/cpp/utility/variant/monostate>`_
  338. * `std::variant <https://en.cppreference.com/w/cpp/utility/variant/variant>`_
  339. Formatting Variants
  340. -------------------
  341. A ``std::variant`` is only formattable if every variant alternative is formattable, and requires the
  342. ``__cpp_lib_variant`` `library feature <https://en.cppreference.com/w/cpp/feature_test>`_.
  343. **Example**::
  344. #include <fmt/std.h>
  345. std::variant<char, float> v0{'x'};
  346. // Prints "variant('x')"
  347. fmt::print("{}", v0);
  348. std::variant<std::monostate, char> v1;
  349. // Prints "variant(monostate)"
  350. .. _compile-api:
  351. Format String Compilation
  352. =========================
  353. ``fmt/compile.h`` provides format string compilation enabled via the
  354. ``FMT_COMPILE`` macro or the ``_cf`` user-defined literal. Format strings
  355. marked with ``FMT_COMPILE`` or ``_cf`` are parsed, checked and converted into
  356. efficient formatting code at compile-time. This supports arguments of built-in
  357. and string types as well as user-defined types with ``constexpr`` ``parse``
  358. functions in their ``formatter`` specializations. Format string compilation can
  359. generate more binary code compared to the default API and is only recommended in
  360. places where formatting is a performance bottleneck.
  361. .. doxygendefine:: FMT_COMPILE
  362. .. doxygenfunction:: operator""_cf()
  363. .. _color-api:
  364. Terminal Color and Text Style
  365. =============================
  366. ``fmt/color.h`` provides support for terminal color and text style output.
  367. .. doxygenfunction:: print(const text_style &ts, const S &format_str, const Args&... args)
  368. .. doxygenfunction:: fg(detail::color_type)
  369. .. doxygenfunction:: bg(detail::color_type)
  370. .. doxygenfunction:: styled(const T& value, text_style ts)
  371. .. _os-api:
  372. System APIs
  373. ===========
  374. .. doxygenclass:: fmt::ostream
  375. :members:
  376. .. doxygenfunction:: fmt::windows_error
  377. :members:
  378. .. _ostream-api:
  379. ``std::ostream`` Support
  380. ========================
  381. ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
  382. user-defined types that have an overloaded insertion operator (``operator<<``).
  383. In order to make a type formattable via ``std::ostream`` you should provide a
  384. ``formatter`` specialization inherited from ``ostream_formatter``::
  385. #include <fmt/ostream.h>
  386. struct date {
  387. int year, month, day;
  388. friend std::ostream& operator<<(std::ostream& os, const date& d) {
  389. return os << d.year << '-' << d.month << '-' << d.day;
  390. }
  391. };
  392. template <> struct fmt::formatter<date> : ostream_formatter {};
  393. std::string s = fmt::format("The date is {}", date{2012, 12, 9});
  394. // s == "The date is 2012-12-9"
  395. .. doxygenfunction:: streamed(const T &)
  396. .. doxygenfunction:: print(std::ostream &os, format_string<T...> fmt, T&&... args)
  397. .. _printf-api:
  398. ``printf`` Formatting
  399. =====================
  400. The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
  401. The following functions use `printf format string syntax
  402. <https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
  403. the POSIX extension for positional arguments. Unlike their standard
  404. counterparts, the ``fmt`` functions are type-safe and throw an exception if an
  405. argument type doesn't match its format specification.
  406. .. doxygenfunction:: printf(const S &format_str, const T&... args)
  407. .. doxygenfunction:: fprintf(std::FILE *f, const S &fmt, const T&... args) -> int
  408. .. doxygenfunction:: sprintf(const S&, const T&...)
  409. .. _xchar-api:
  410. ``wchar_t`` Support
  411. ===================
  412. The optional header ``fmt/xchar.h`` provides support for ``wchar_t`` and exotic
  413. character types.
  414. .. doxygenstruct:: fmt::is_char
  415. .. doxygentypedef:: fmt::wstring_view
  416. .. doxygentypedef:: fmt::wformat_context
  417. .. doxygenfunction:: fmt::to_wstring(const T &value)
  418. Compatibility with C++20 ``std::format``
  419. ========================================
  420. {fmt} implements nearly all of the `C++20 formatting library
  421. <https://en.cppreference.com/w/cpp/utility/format>`_ with the following
  422. differences:
  423. * Names are defined in the ``fmt`` namespace instead of ``std`` to avoid
  424. collisions with standard library implementations.
  425. * Width calculation doesn't use grapheme clusterization. The latter has been
  426. implemented in a separate branch but hasn't been integrated yet.
  427. * Most C++20 chrono types are not supported yet.