API Reference

The {fmt} library API consists of the following parts:

All functions and types provided by the library reside in namespace fmt and macros have prefix FMT_.

Core API

fmt/core.h defines the core API which provides main formatting functions for char/UTF-8 with C++20 compile-time checks. It has minimal include dependencies for better compile times. This header is only beneficial when using {fmt} as a library (the default) and not in the header-only mode. It also provides formatter specializations for built-in and string types.

The following functions use format string syntax similar to that of Python’s str.format. They take fmt and args as arguments.

fmt is a format string that contains literal text and replacement fields surrounded by braces {}. The fields are replaced with formatted arguments in the resulting string. format_string is a format string which can be implicitly constructed from a string literal or a constexpr string and is checked at compile time in C++20. To pass a runtime format string wrap it in fmt::runtime().

args is an argument list representing objects to be formatted.

I/O errors are reported as std::system_error exceptions unless specified otherwise.

template<typename ...T>
inline std::string fmt::format(format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt and returns the result as a string.

Example:

#include <fmt/core.h>
std::string message = fmt::format("The answer is {}.", 42);

std::string fmt::vformat(string_view fmt, format_args args)
template<typename OutputIt, typename ...T>
inline OutputIt fmt::format_to(OutputIt out, format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt, writes the result to the output iterator out and returns the iterator past the end of the output range. format_to() does not append a terminating null character.

Example:

auto out = std::vector<char>();
fmt::format_to(std::back_inserter(out), "{}", 42);

template<typename OutputIt, typename ...T>
inline format_to_n_result<OutputIt> fmt::format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt, writes up to n characters of the result to the output iterator out and returns the total (not truncated) output size and the iterator past the end of the output range. format_to_n() does not append a terminating null character.

template<typename ...T>
inline size_t fmt::formatted_size(format_string<T...> fmt, T&&... args)

Returns the number of chars in the output of format(fmt, args...).

template<typename OutputIt>
struct format_to_n_result

Public Members

OutputIt out

Iterator past the end of the output range.

size_t size

Total (not truncated) output size.

template<typename ...T>
inline void fmt::print(format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt and writes the output to stdout.

Example:

fmt::print("Elapsed time: {0:.2f} seconds", 1.23);

void fmt::vprint(string_view fmt, format_args args)
template<typename ...T>
inline void fmt::print(std::FILE *f, format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt and writes the output to the file f.

Example:

fmt::print(stderr, "Don't {}!", "panic");

void fmt::vprint(std::FILE *f, string_view fmt, format_args args)

Compile-Time Format String Checks

Compile-time format string checks are enabled by default on compilers that support C++20 consteval. On older compilers you can use the FMT_STRING: macro defined in fmt/format.h instead.

Unused arguments are allowed as in Python’s str.format and ordinary functions.

template<typename Char, typename ...Args>
class basic_format_string

A compile-time format string.

template<typename ...Args>
using fmt::format_string = basic_format_string<char, type_identity_t<Args>...>
inline runtime_format_string<> fmt::runtime(string_view s)

Creates a runtime format string.

Example:

// Check format string at runtime instead of compile-time.
fmt::print(fmt::runtime("{:d}"), "I am not a number");

Formatting User-Defined Types

The {fmt} library provides formatters for many standard C++ types. See fmt/ranges.h for ranges and tuples including standard containers such as std::vector, fmt/chrono.h for date and time formatting and fmt/std.h for other standard library types.

There are two ways to make a user-defined type formattable: providing a format_as function or specializing the formatter struct template.

Use format_as if you want to make your type formattable as some other type with the same format specifiers. The format_as function should take an object of your type and return an object of a formattable type. It should be defined in the same namespace as your type.

Example (https://godbolt.org/z/nvME4arz8):

#include <fmt/format.h>

namespace kevin_namespacy {
enum class film {
  house_of_cards, american_beauty, se7en = 7
};
auto format_as(film f) { return fmt::underlying(f); }
}

int main() {
  fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7"
}

Using specialization is more complex but gives you full control over parsing and formatting. To use this method specialize the formatter struct template for your type and implement parse and format methods.

The recommended way of defining a formatter is by reusing an existing one via inheritance or composition. This way you can support standard format specifiers without implementing them yourself. For example:

// color.h:
#include <fmt/core.h>

enum class color {red, green, blue};

template <> struct fmt::formatter<color>: formatter<string_view> {
  // parse is inherited from formatter<string_view>.

  auto format(color c, format_context& ctx) const;
};

// color.cc:
#include "color.h"
#include <fmt/format.h>

auto fmt::formatter<color>::format(color c, format_context& ctx) const {
  string_view name = "unknown";
  switch (c) {
  case color::red:   name = "red"; break;
  case color::green: name = "green"; break;
  case color::blue:  name = "blue"; break;
  }
  return formatter<string_view>::format(name, ctx);
}

Note that formatter<string_view>::format is defined in fmt/format.h so it has to be included in the source file. Since parse is inherited from formatter<string_view> it will recognize all string format specifications, for example

fmt::format("{:>10}", color::blue)

will return "      blue".

The experimental nested_formatter provides an easy way of applying a formatter to one or more subobjects.

For example:

#include <fmt/format.h>

struct point {
  double x, y;
};

template <>
struct fmt::formatter<point> : nested_formatter<double> {
  auto format(point p, format_context& ctx) const {
    return write_padded(ctx, [=](auto out) {
      return format_to(out, "({}, {})", nested(p.x), nested(p.y));
    });
  }
};

int main() {
  fmt::print("[{:>20.2f}]", point{1, 2});
}

prints:

[          (1.00, 2.00)]

Notice that fill, align and width are applied to the whole object which is the recommended behavior while the remaining specifiers apply to elements.

In general the formatter has the following form:

template <> struct fmt::formatter<T> {
  // Parses format specifiers and stores them in the formatter.
  //
  // [ctx.begin(), ctx.end()) is a, possibly empty, character range that
  // contains a part of the format string starting from the format
  // specifications to be parsed, e.g. in
  //
  //   fmt::format("{:f} continued", ...);
  //
  // the range will contain "f} continued". The formatter should parse
  // specifiers until '}' or the end of the range. In this example the
  // formatter should parse the 'f' specifier and return an iterator
  // pointing to '}'.
  constexpr auto parse(format_parse_context& ctx)
    -> format_parse_context::iterator;

  // Formats value using the parsed format specification stored in this
  // formatter and writes the output to ctx.out().
  auto format(const T& value, format_context& ctx) const
    -> format_context::iterator;
};

It is recommended to at least support fill, align and width that apply to the whole object and have the same semantics as in standard formatters.

You can also write a formatter for a hierarchy of classes:

// demo.h:
#include <type_traits>
#include <fmt/core.h>

struct A {
  virtual ~A() {}
  virtual std::string name() const { return "A"; }
};

struct B : A {
  virtual std::string name() const { return "B"; }
};

template <typename T>
struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
    fmt::formatter<std::string> {
  auto format(const A& a, format_context& ctx) const {
    return fmt::formatter<std::string>::format(a.name(), ctx);
  }
};

// demo.cc:
#include "demo.h"
#include <fmt/format.h>

int main() {
  B b;
  A& a = b;
  fmt::print("{}", a); // prints "B"
}

Providing both a formatter specialization and a format_as overload is disallowed.

Named Arguments

Warning

doxygenfunction: Unable to resolve function “fmt::arg” with arguments (const S&, const T&) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:

- template<typename Char, typename T> detail::named_arg<Char, T> arg(const Char *name, const T &arg)

Named arguments are not supported in compile-time checks at the moment.

Argument Lists

You can create your own formatting function with compile-time checks and small binary footprint, for example (https://godbolt.org/z/vajfWEG4b):

#include <fmt/core.h>

void vlog(const char* file, int line, fmt::string_view format,
          fmt::format_args args) {
  fmt::print("{}: {}: ", file, line);
  fmt::vprint(format, args);
}

template <typename... T>
void log(const char* file, int line, fmt::format_string<T...> format, T&&... args) {
  vlog(file, line, format, fmt::make_format_args(args...));
}

#define MY_LOG(format, ...) log(__FILE__, __LINE__, format, __VA_ARGS__)

MY_LOG("invalid squishiness: {}", 42);

Note that vlog is not parameterized on argument types which improves compile times and reduces binary code size compared to a fully parameterized version.

Warning

doxygenfunction: Unable to resolve function “fmt::make_format_args” with arguments (const Args&…) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:

- template<typename Context = format_context, typename ...T> format_arg_store<Context, remove_cvref_t<T>...> make_format_args(T&... args)
template<typename Context, typename ...Args>
class format_arg_store

An array of references to arguments. It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

template<typename Context>
class basic_format_args

A view of a collection of formatting arguments. To avoid lifetime issues it should only be used as a parameter type in type-erased functions such as vformat:

void vlog(string_view format_str, format_args args);  // OK
format_args args = make_format_args();  // Error: dangling reference

Public Functions

template<typename ...Args>
inline constexpr basic_format_args(const format_arg_store<Context, Args...> &store)

Constructs a basic_format_args() object from format_arg_store.

inline constexpr basic_format_args(const dynamic_format_arg_store<Context> &store)

Constructs a basic_format_args() object from dynamic_format_arg_store.

inline constexpr basic_format_args(const format_arg *args, int count)

Constructs a basic_format_args() object from a dynamic set of arguments.

inline format_arg get(int id) const

Returns the argument with the specified id.

using fmt::format_args = basic_format_args<format_context>

An alias to basic_format_args<format_context>.

template<typename Context>
class basic_format_arg
template<typename Char>
class basic_format_parse_context

Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing. You can use the format_parse_context type alias for char instead.

Subclassed by fmt::detail::compile_parse_context< Char >

Public Functions

inline iterator begin() const noexcept

Returns an iterator to the beginning of the format string range being parsed.

inline iterator end() const noexcept

Returns an iterator past the end of the format string range being parsed.

inline void advance_to(iterator it)

Advances the begin iterator to it.

inline int next_arg_id()

Reports an error if using the manual argument indexing; otherwise returns the next argument index and switches to the automatic indexing.

inline void check_arg_id(int id)

Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.

template<typename OutputIt, typename Char>
class basic_format_context

Public Types

using char_type = Char

The character type for the output.

Public Functions

inline constexpr basic_format_context(OutputIt out, format_args ctx_args, detail::locale_ref loc = {})

Constructs a basic_format_context object.

References to the arguments are stored in the object so make sure they have appropriate lifetimes.

using fmt::format_context = buffer_context<char>

Dynamic Argument Lists

The header fmt/args.h provides dynamic_format_arg_store, a builder-like API that can be used to construct format argument lists dynamically.

template<typename Context>
class dynamic_format_arg_store

A dynamic version of fmt::format_arg_store. It’s equipped with a storage to potentially temporary objects which lifetimes could be shorter than the format arguments object.

It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

Public Functions

template<typename T>
inline void push_back(const T &arg)

Adds an argument into the dynamic store for later passing to a formatting function.

Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary.

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
store.push_back(42);
store.push_back("abc");
store.push_back(1.5f);
std::string result = fmt::vformat("{} and {} and {}", store);

template<typename T>
inline void push_back(std::reference_wrapper<T> arg)

Adds a reference to the argument into the dynamic store for later passing to a formatting function.

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
char band[] = "Rolling Stones";
store.push_back(std::cref(band));
band[9] = 'c'; // Changing str affects the output.
std::string result = fmt::vformat("{}", store);
// result == "Rolling Scones"

template<typename T>
inline void push_back(const detail::named_arg<char_type, T> &arg)

Adds named argument into the dynamic store for later passing to a formatting function.

std::reference_wrapper is supported to avoid copying of the argument. The name is always copied into the store.

inline void clear()

Erase all elements from the store.

inline void reserve(size_t new_cap, size_t new_cap_named)

Reserves space to store at least new_cap arguments including new_cap_named named arguments.

Compatibility

template<typename Char>
class basic_string_view

An implementation of std::basic_string_view for pre-C++17.

It provides a subset of the API. fmt::basic_string_view is used for format strings even if std::string_view is available to prevent issues when a library is compiled with a different -std option than the client code (which is not recommended).

Public Functions

inline constexpr basic_string_view(const Char *s, size_t count) noexcept

Constructs a string reference object from a C string and a size.

inline basic_string_view(const Char *s)

Constructs a string reference object from a C string computing the size with std::char_traits<Char>::length.

template<typename Traits, typename Alloc>
inline basic_string_view(const std::basic_string<Char, Traits, Alloc> &s) noexcept

Constructs a string reference from a std::basic_string object.

inline const Char *data() const noexcept

Returns a pointer to the string data.

inline size_t size() const noexcept

Returns the string size.

using fmt::string_view = basic_string_view<char>

Format API

fmt/format.h defines the full format API providing additional formatting functions and locale support.

Literal-Based API

The following user-defined literals are defined in fmt/format.h.

template<detail_exported::fixed_string Str>
auto fmt::operator""_a()

User-defined literal equivalent of fmt::arg().

Example:

using namespace fmt::literals;
fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);

Utilities

template<typename T>
const void *fmt::ptr(T p)

Converts p to const void* for pointer formatting.

Example:

auto s = fmt::format("{}", fmt::ptr(p));

template<typename T, typename Deleter>
const void *fmt::ptr(const std::unique_ptr<T, Deleter> &p)
template<typename T>
const void *fmt::ptr(const std::shared_ptr<T> &p)
template<typename Enum>
underlying_t<Enum> fmt::underlying(Enum e) noexcept

Converts e to the underlying type.

Example:

enum class color { red, green, blue };
auto s = fmt::format("{}", fmt::underlying(color::red));

template<typename T>
inline std::string fmt::to_string(const T &value)

Converts value to std::string using the default format for type T.

Example:

#include <fmt/format.h>

std::string answer = fmt::to_string(42);

template<typename Range>
join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>> fmt::join(Range &&range, string_view sep)

Returns a view that formats range with elements separated by sep.

Example:

std::vector<int> v = {1, 2, 3};
fmt::print("{}", fmt::join(v, ", "));
// Output: "1, 2, 3"

fmt::join applies passed format specifiers to the range elements:

fmt::print("{:02}", fmt::join(v, ", "));
// Output: "01, 02, 03"

template<typename It, typename Sentinel>
join_view<It, Sentinel> fmt::join(It begin, Sentinel end, string_view sep)

Returns a view that formats the iterator range [begin, end) with elements separated by sep.

template<typename T>
group_digits_view<T> fmt::group_digits(T value)

Returns a view that formats an integer value using ‘,’ as a locale-independent thousands separator.

Example:

fmt::print("{}", fmt::group_digits(12345));
// Output: "12,345"

template<typename T>
class buffer

A contiguous memory buffer with an optional growing ability. It is an internal class and shouldn’t be used directly, only via basic_memory_buffer.

Subclassed by fmt::basic_memory_buffer< T, SIZE, Allocator >, fmt::detail::iterator_buffer< OutputIt, T, Traits >, fmt::detail::iterator_buffer< T *, T >, fmt::detail::iterator_buffer< T *, T, fixed_buffer_traits >

Public Functions

inline size_t size() const noexcept

Returns the size of this buffer.

inline size_t capacity() const noexcept

Returns the capacity of this buffer.

inline T *data() noexcept

Returns a pointer to the buffer data (not null-terminated).

inline void clear()

Clears this buffer.

template<typename U>
void append(const U *begin, const U *end)

Appends data to the end of the buffer.

template<typename T, size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class basic_memory_buffer : public fmt::detail::buffer<T>

A dynamically growing memory buffer for trivially copyable/constructible types with the first SIZE elements stored in the object itself.

You can use the memory_buffer type alias for char instead.

Example:

auto out = fmt::memory_buffer();
fmt::format_to(std::back_inserter(out), "The answer is {}.", 42);

This will append the following output to the out object:

The answer is 42.

The output can be converted to an std::string with to_string(out).

Public Functions

inline basic_memory_buffer(basic_memory_buffer &&other) noexcept

Constructs a fmt::basic_memory_buffer object moving the content of the other object to it.

inline basic_memory_buffer &operator=(basic_memory_buffer &&other) noexcept

Moves the content of the other basic_memory_buffer object to this one.

inline void resize(size_t count)

Resizes the buffer to contain count elements.

If T is a POD type new elements may not be initialized.

inline void reserve(size_t new_capacity)

Increases the buffer capacity to new_capacity.

Protected Functions

inline virtual void grow(size_t size) override

Increases the buffer capacity to hold at least capacity elements.

System Errors

{fmt} does not use errno to communicate errors to the user, but it may call system functions which set errno. Users should not make any assumptions about the value of errno being preserved by library functions.

template<typename ...T>
std::system_error fmt::system_error(int error_code, format_string<T...> fmt, T&&... args)

Constructs std::system_error with a message formatted with fmt::format(fmt, args...). error_code is a system error code as given by errno.

Example:

// This throws std::system_error with the description
//   cannot open file 'madeup': No such file or directory
// or similar (system message may vary).
const char* filename = "madeup";
std::FILE* file = std::fopen(filename, "r");
if (!file)
  throw fmt::system_error(errno, "cannot open file '{}'", filename);

void fmt::format_system_error(detail::buffer<char> &out, int error_code, const char *message) noexcept

Formats an error message for an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out. The format is the same as the one used by std::system_error(ec, message) where ec is std::error_code(error_code, std::generic_category()}). It is implementation-defined but normally looks like:

<message>: <system-message>

where <message> is the passed message and <system-message> is the system message corresponding to the error code. error_code is a system error code as given by errno.

Custom Allocators

The {fmt} library supports custom dynamic memory allocators. A custom allocator class can be specified as a template argument to fmt::basic_memory_buffer:

using custom_memory_buffer =
  fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;

It is also possible to write a formatting function that uses a custom allocator:

using custom_string =
  std::basic_string<char, std::char_traits<char>, custom_allocator>;

custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
                      fmt::format_args args) {
  auto buf = custom_memory_buffer(alloc);
  fmt::vformat_to(std::back_inserter(buf), format_str, args);
  return custom_string(buf.data(), buf.size(), alloc);
}

template <typename ...Args>
inline custom_string format(custom_allocator alloc,
                            fmt::string_view format_str,
                            const Args& ... args) {
  return vformat(alloc, format_str, fmt::make_format_args(args...));
}

The allocator will be used for the output container only. Formatting functions normally don’t do any allocations for built-in and string types except for non-default floating-point formatting that occasionally falls back on sprintf.

Locale

All formatting is locale-independent by default. Use the 'L' format specifier to insert the appropriate number separator characters from the locale:

#include <fmt/core.h>
#include <locale>

std::locale::global(std::locale("en_US.UTF-8"));
auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"

fmt/format.h provides the following overloads of formatting functions that take std::locale as a parameter. The locale type is a template parameter to avoid the expensive <locale> include.

template<typename Locale, typename ...T>
inline std::string fmt::format(const Locale &loc, format_string<T...> fmt, T&&... args)
template<typename OutputIt, typename Locale, typename ...T>
inline OutputIt fmt::format_to(OutputIt out, const Locale &loc, format_string<T...> fmt, T&&... args)
template<typename Locale, typename ...T>
inline size_t fmt::formatted_size(const Locale &loc, format_string<T...> fmt, T&&... args)

Legacy Compile-Time Format String Checks

FMT_STRING enables compile-time checks on older compilers. It requires C++14 or later and is a no-op in C++11.

FMT_STRING(s)

Constructs a compile-time format string from a string literal s.

Example:

// A compile-time error because 'd' is an invalid specifier for strings.
std::string s = fmt::format(FMT_STRING("{:d}"), "foo");

To force the use of legacy compile-time checks, define the preprocessor variable FMT_ENFORCE_COMPILE_STRING. When set, functions accepting FMT_STRING will fail to compile with regular strings.

Range and Tuple Formatting

The library also supports convenient formatting of ranges and tuples:

#include <fmt/ranges.h>

std::tuple<char, int, float> t{'a', 1, 2.0f};
// Prints "('a', 1, 2.0)"
fmt::print("{}", t);

NOTE: currently, the overload of fmt::join for iterables exists in the main format.h header, but expect this to change in the future.

Using fmt::join, you can separate tuple elements with a custom separator:

#include <fmt/ranges.h>

std::tuple<int, char> t = {1, 'a'};
// Prints "1, a"
fmt::print("{}", fmt::join(t, ", "));

Date and Time Formatting

fmt/chrono.h provides formatters for

The format syntax is described in Chrono Format Specifications.

Example:

#include <fmt/chrono.h>

int main() {
  std::time_t t = std::time(nullptr);

  // Prints "The date is 2020-11-07." (with the current date):
  fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));

  using namespace std::literals::chrono_literals;

  // Prints "Default format: 42s 100ms":
  fmt::print("Default format: {} {}\n", 42s, 100ms);

  // Prints "strftime-like format: 03:15:30":
  fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
}
inline std::tm fmt::localtime(std::time_t time)

Converts given time since epoch as std::time_t value into calendar time, expressed in local time.

Unlike std::localtime, this function is thread-safe on most platforms.

inline std::tm fmt::gmtime(std::time_t time)

Converts given time since epoch as std::time_t value into calendar time, expressed in Coordinated Universal Time (UTC).

Unlike std::gmtime, this function is thread-safe on most platforms.

Standard Library Types Formatting

fmt/std.h provides formatters for:

Formatting Variants

A std::variant is only formattable if every variant alternative is formattable, and requires the __cpp_lib_variant library feature.

Example:

#include <fmt/std.h>

std::variant<char, float> v0{'x'};
// Prints "variant('x')"
fmt::print("{}", v0);

std::variant<std::monostate, char> v1;
// Prints "variant(monostate)"

Format String Compilation

fmt/compile.h provides format string compilation enabled via the FMT_COMPILE macro or the _cf user-defined literal. Format strings marked with FMT_COMPILE or _cf are parsed, checked and converted into efficient formatting code at compile-time. This supports arguments of built-in and string types as well as user-defined types with format functions taking the format context type as a template parameter in their formatter specializations. For example:

template <> struct fmt::formatter<point> {
  constexpr auto parse(format_parse_context& ctx);

  template <typename FormatContext>
  auto format(const point& p, FormatContext& ctx) const;
};

Format string compilation can generate more binary code compared to the default API and is only recommended in places where formatting is a performance bottleneck.

FMT_COMPILE(s)

Converts a string literal s into a format string that will be parsed at compile time and converted into efficient formatting code. Requires C++17 constexpr if compiler support.

Example:

// Converts 42 into std::string using the most efficient method and no
// runtime format string processing.
std::string s = fmt::format(FMT_COMPILE("{}"), 42);

template<detail_exported::fixed_string Str>
auto fmt::operator""_cf()

Terminal Color and Text Style

fmt/color.h provides support for terminal color and text style output.

template<typename S, typename ...Args>
void fmt::print(const text_style &ts, const S &format_str, const Args&... args)

Formats a string and prints it to stdout using ANSI escape sequences to specify text formatting.

Example:

fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
           "Elapsed time: {0:.2f} seconds", 1.23);

Warning

doxygenfunction: Unable to resolve function “fg” with arguments (detail::color_type) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:

- text_style fg(detail::color_type foreground)
- text_style fg(detail::color_type foreground)

Warning

doxygenfunction: Unable to resolve function “bg” with arguments (detail::color_type) in doxygen xml output for project “format” from directory: /build/fmt/src/build/doc/doxyxml. Potential matches:

- text_style bg(detail::color_type background)
- text_style bg(detail::color_type background)
template<typename T>
detail::styled_arg<remove_cvref_t<T>> fmt::styled(const T &value, text_style ts)

Returns an argument that will be formatted using ANSI escape sequences, to be used in a formatting function.

Example:

fmt::print("Elapsed time: {0:.2f} seconds",
           fmt::styled(1.23, fmt::fg(fmt::color::green) |
                             fmt::bg(fmt::color::blue)));

System APIs

class ostream

A fast output stream which is not thread-safe.

Public Functions

template<typename ...T>
inline void print(format_string<T...> fmt, T&&... args)

Formats args according to specifications in fmt and writes the output to the file.

Friends

template<typename ...T>
friend ostream output_file(cstring_view path, T... params)

Opens a file for writing. Supported parameters passed in params:

  • <integer>: Flags passed to open (file::WRONLY | file::CREATE | file::TRUNC by default)

  • buffer_size=<integer>: Output buffer size

Example:

auto out = fmt::output_file("guide.txt");
out.print("Don't {}", "Panic");

template<typename ...Args>
std::system_error fmt::windows_error(int error_code, string_view message, const Args&... args)

Constructs a std::system_error object with the description of the form

<message>: <system-message>

where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a Windows error code as given by GetLastError. If error_code is not a valid error code such as -1, the system message will look like “error -1”.

Example:

// This throws a system_error with the description
//   cannot open file 'madeup': The system cannot find the file specified.
// or similar (system message may vary).
const char *filename = "madeup";
LPOFSTRUCT of = LPOFSTRUCT();
HFILE file = OpenFile(filename, &of, OF_READ);
if (file == HFILE_ERROR) {
  throw fmt::windows_error(GetLastError(),
                           "cannot open file '{}'", filename);
}

std::ostream Support

fmt/ostream.h provides std::ostream support including formatting of user-defined types that have an overloaded insertion operator (operator<<). In order to make a type formattable via std::ostream you should provide a formatter specialization inherited from ostream_formatter:

#include <fmt/ostream.h>

struct date {
  int year, month, day;

  friend std::ostream& operator<<(std::ostream& os, const date& d) {
    return os << d.year << '-' << d.month << '-' << d.day;
  }
};

template <> struct fmt::formatter<date> : ostream_formatter {};

std::string s = fmt::format("The date is {}", date{2012, 12, 9});
// s == "The date is 2012-12-9"
template<typename T>
detail::streamed_view<T> fmt::streamed(const T &value)

Returns a view that formats value via an ostream operator<<.

Example:

fmt::print("Current thread id: {}\n",
           fmt::streamed(std::this_thread::get_id()));

template<typename ...T>
void fmt::print(std::ostream &os, format_string<T...> fmt, T&&... args)

Prints formatted data to the stream os.

Example:

fmt::print(cerr, "Don't {}!", "panic");

printf Formatting

The header fmt/printf.h provides printf-like formatting functionality. The following functions use printf format string syntax with the POSIX extension for positional arguments. Unlike their standard counterparts, the fmt functions are type-safe and throw an exception if an argument type doesn’t match its format specification.

template<typename ...T>
inline int fmt::printf(string_view fmt, const T&... args)

Prints formatted data to stdout.

Example:

fmt::printf("Elapsed time: %.2f seconds", 1.23);

template<typename S, typename ...T, typename Char = char_t<S>>
inline int fmt::fprintf(std::FILE *f, const S &fmt, const T&... args)

Prints formatted data to the file f.

Example:

fmt::fprintf(stderr, "Don't %s!", "panic");

template<typename S, typename ...T, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
inline std::basic_string<Char> fmt::sprintf(const S &fmt, const T&... args)

Formats arguments and returns the result as a string.

Example:

std::string message = fmt::sprintf("The answer is %d", 42);

wchar_t Support

The optional header fmt/xchar.h provides support for wchar_t and exotic character types.

template<typename T>
struct is_char : public std::false_type

Specifies if T is a character type.

Can be specialized by users.

using fmt::wstring_view = basic_string_view<wchar_t>
using fmt::wformat_context = buffer_context<wchar_t>
template<typename T>
inline std::wstring fmt::to_wstring(const T &value)

Converts value to std::wstring using the default format for type T.

Compatibility with C++20 std::format

{fmt} implements nearly all of the C++20 formatting library with the following differences:

  • Names are defined in the fmt namespace instead of std to avoid collisions with standard library implementations.

  • Width calculation doesn’t use grapheme clusterization. The latter has been implemented in a separate branch but hasn’t been integrated yet.

  • Most C++20 chrono types are not supported yet.