API Reference

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

  • fmt/core.h: the core API providing argument handling facilities and a lightweight subset of formatting functions

  • fmt/format.h: the full format API providing compile-time format string checks, output iterator and user-defined type support

  • fmt/time.h: date and time formatting

  • fmt/ostream.h: std::ostream support

  • fmt/printf.h: printf formatting

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

Core API

fmt/core.h defines the core API which provides argument handling facilities and a lightweight subset of formatting functions.

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

format_str 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. A function taking format_str doesn’t participate in an overload resolution if the latter is not a string.

args is an argument list representing objects to be formatted.

template<typename S, typename ...Args>
std::basic_string<fmt::char_t<S>> fmt::format(const S &format_str, const Args&... args)

Formats arguments and returns the result as a string.

Example:

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

template<typename S, typename Char = fmt::char_t<S>>
std::basic_string<Char> fmt::vformat(const S &format_str, basic_format_args<typename buffer_context<Char>::type> args)
template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value, void>::type fmt::print(const S &format_str, const Args&... args)

Prints formatted data to stdout.

Example:

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

void fmt::vprint(string_view format_str, format_args args)
template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value, void>::type fmt::print(std::FILE *f, const S &format_str, const Args&... args)

Prints formatted data to the file f. For wide format strings, f should be in wide-oriented mode set via fwide(f, 1) or _setmode(_fileno(f), _O_U8TEXT) on Windows.

Example:

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

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

Named arguments

template<typename T>
internal::named_arg<T, char> fmt::arg(string_view name, const T &arg)

Returns a named argument to be used in a formatting function.

Example:

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

Argument lists

template<typename Context = format_context, typename ...Args>
format_arg_store<Context, Args...> fmt::make_format_args(const Args&... args)

Constructs an format_arg_store object that contains references to arguments and can be implicitly converted to format_args. Context can be omitted in which case it defaults to context.

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().

Subclassed by fmt::internal::checked_args< S, Args >

template<typename Context>
class fmt::basic_format_args

Formatting arguments.

Subclassed by fmt::format_args, fmt::wformat_args

Public Functions

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

Constructs a basic_format_args() object from format_arg_store.

basic_format_args(const format_arg *args, size_type count)

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

format_arg get(size_type index) const

Returns the argument at specified index.

struct format_args : public fmt::basic_format_args<format_context>

An alias to basic_format_args<context>.

template<typename Context>
class basic_format_arg

Compatibility

template<typename Char>
class fmt::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).

Subclassed by fmt::u8string_view

Public Functions

basic_string_view(const Char *s, size_t count)

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

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 Alloc>
basic_string_view(const std::basic_string<Char, Alloc> &s)

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

const Char *data() const

Returns a pointer to the string data.

size_t size() const

Returns the string size.

typedef basic_string_view<char> fmt::string_view
typedef basic_string_view<wchar_t> fmt::wstring_view

Format API

fmt/format.h defines the full format API providing compile-time format string checks, output iterator and user-defined type support.

Compile-time format string checks

fmt(s)

Constructs a compile-time format string. This macro is disabled by default to prevent potential name collisions. To enable it define FMT_STRING_ALIAS to 1 before including fmt/format.h.

Example:

#define FMT_STRING_ALIAS 1
#include <fmt/format.h>
// A compile-time error because 'd' is an invalid specifier for strings.
std::string s = format(fmt("{:d}"), "foo");

Formatting user-defined types

To make a user-defined type formattable, specialize the formatter<T> struct template and implement parse and format methods:

#include <fmt/format.h>

struct point { double x, y; };

namespace fmt {
template <>
struct formatter<point> {
  template <typename ParseContext>
  constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }

  template <typename FormatContext>
  auto format(const point &p, FormatContext &ctx) {
    return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
  }
};
}

Then you can pass objects of type point to any formatting function:

point p = {1, 2};
std::string s = fmt::format("{}", p);
// s == "(1.0, 2.0)"

In the example above the formatter<point>::parse function ignores the contents of the format string referred to by ctx.begin() so the object will always be formatted in the same way. See formatter<tm>::parse in fmt/time.h for an advanced example of how to parse the format string and customize the formatted output.

You can also reuse existing formatters, for example:

enum class color {red, green, blue};

template <>
struct fmt::formatter<color>: formatter<string_view> {
  // parse is inherited from formatter<string_view>.
  template <typename FormatContext>
  auto format(color c, FormatContext &ctx) {
    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);
  }
};

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

#include <type_traits>
#include <fmt/format.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> {
  template <typename FormatCtx>
  auto format(const A& a, FormatCtx& ctx) {
    return fmt::formatter<std::string>::format(a.name(), ctx);
  }
};

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

This section shows how to define a custom format function for a user-defined type. The next section describes how to get fmt to use a conventional stream output operator<< when one is defined for a user-defined type.

Output iterator support

template<typename OutputIt, typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value && internal::is_output_iterator<OutputIt>::value, OutputIt>::type fmt::format_to(OutputIt out, const S &format_str, const Args&... args)

Formats arguments, writes the result to the output iterator out and returns the iterator past the end of the output range.

Example:

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

template<typename OutputIt, typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value && internal::is_output_iterator<OutputIt>::value, format_to_n_result<OutputIt>>::type fmt::format_to_n(OutputIt out, std::size_t n, const S &format_str, const Args&... args)

Formats arguments, writes up to n characters of the result to the output iterator out and returns the total output size and the iterator past the end of the output range.

template<typename OutputIt>
struct fmt::format_to_n_result

Public Members

OutputIt out

Iterator past the end of the output range.

std::size_t size

Total (not truncated) output size.

Literal-based API

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

internal::udl_formatter<char> fmt::operator""_format(const char *s, std::size_t)

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

Example:

using namespace fmt::literals;
std::string message = "The answer is {}"_format(42);

internal::udl_arg<char> fmt::operator""_a(const char *s, std::size_t)

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 S>
using fmt::char_t = typename std::enable_if<internal::is_string<S>::value, typename internal::char_t<S>::type>::type

String’s character type.

template<typename ...Args>
std::size_t fmt::formatted_size(string_view format_str, const Args&... args)

Returns the number of characters in the output of format(format_str, args...).

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

Converts value to std::string using the default format for type T. It doesn’t support user-defined types with custom formatters.

Example:

#include <fmt/format.h>

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

template<typename T>
std::wstring fmt::to_wstring(const T &value)

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

template<typename Char>
basic_string_view<Char> fmt::to_string_view(basic_string_view<Char> s)

The function to_string_view adapts non-intrusively any kind of string or string-like type if the user provides a (possibly templated) overload of to_string_view which takes an instance of the string class StringType<Char> and returns a fmt::basic_string_view<Char>. The conversion function must live in the very same namespace as StringType<Char> to be picked up by ADL. Non-templated string types like f.e. QString must return a basic_string_view with a fixed matching char type.

Example:

namespace my_ns {
inline string_view to_string_view(const my_string &s) {
  return {s.data(), s.length()};
}
}

std::string message = fmt::format(my_string("The answer is {}"), 42);

template<typename T, std::size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class fmt::basic_memory_buffer : private std::allocator<T>, public fmt::internal::basic_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 one of the following typedefs for common character types:

Type

Definition

memory_buffer

basic_memory_buffer<char>

wmemory_buffer

basic_memory_buffer<wchar_t>

Example:

fmt::memory_buffer out;
format_to(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

basic_memory_buffer(basic_memory_buffer &&other)

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

basic_memory_buffer &operator=(basic_memory_buffer &&other)

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

Protected Functions

void grow(std::size_t size)

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.

class fmt::system_error : public std::runtime_error

An error returned by an operating system or a language runtime, for example a file opening error.

Subclassed by fmt::windows_error

Public Functions

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

Constructs a fmt::system_error object with a description formatted with fmt::format_system_error(). message and additional arguments passed into the constructor are formatted similarly to fmt::format().

Example:

// This throws a 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(internal::buffer &out, int error_code, fmt::string_view message)

Formats an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out in the following form:

<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. If error_code is not a valid error code such as -1, the system message may look like “Unknown error -1” and is platform-dependent.

class fmt::windows_error : public fmt::system_error

A Windows error.

Public Functions

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

Constructs a fmt::windows_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 windows_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);
}

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) {
  custom_memory_buffer buf(alloc);
  fmt::vformat_to(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. If you are using named arguments, the container that stores pointers to them will be allocated using the default allocator. Also floating-point formatting falls back on sprintf which may do allocations.

Custom formatting of built-in types

It is possible to change the way arguments are formatted by providing a custom argument formatter class:

using arg_formatter =
  fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>>;

// A custom argument formatter that formats negative integers as unsigned
// with the ``x`` format specifier.
class custom_arg_formatter : public arg_formatter {
 public:
  custom_arg_formatter(fmt::format_context &ctx,
                       fmt::format_specs *spec = nullptr)
    : arg_formatter(ctx, spec) {}

  using arg_formatter::operator();

  auto operator()(int value) {
    if (spec().type() == 'x')
      return (*this)(static_cast<unsigned>(value)); // convert to unsigned and format
    return arg_formatter::operator()(value);
  }
};

std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
  fmt::memory_buffer buffer;
  // Pass custom argument formatter as a template arg to vformat_to.
  fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
  return fmt::to_string(buffer);
}

template <typename ...Args>
inline std::string custom_format(
    fmt::string_view format_str, const Args &... args) {
  return custom_vformat(format_str, fmt::make_format_args(args...));
}

std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
template<typename Range>
class fmt::arg_formatter : public fmt::internal::function<internal::arg_formatter_base<Range>::iterator>, public fmt::internal::arg_formatter_base<Range>

The default argument formatter.

Public Functions

arg_formatter(context_type &ctx, format_specs *spec = NULL)

Constructs an argument formatter object. ctx is a reference to the formatting context, spec contains format specifier information for standard argument types.

iterator operator()(typename basic_format_arg<context_type>::handle handle)

Formats an argument of a user-defined type.

Date and time formatting

The library supports strftime-like date and time formatting:

#include <fmt/time.h>

std::time_t t = std::time(nullptr);
// Prints "The date is 2016-04-29." (with the current date)
fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));

The format string syntax is described in the documentation of strftime.

std::ostream support

fmt/ostream.h provides std::ostream support including formatting of user-defined types that have overloaded operator<<:

#include <fmt/ostream.h>

class date {
  int year_, month_, day_;
public:
  date(int year, int month, int day): year_(year), month_(month), day_(day) {}

  friend std::ostream&operator<<(std::ostream&os, const date &d) {
    return os << d.year_ << '-' << d.month_ << '-' << d.day_;
  }
};

std::string s = fmt::format("The date is {}", date(2012, 12, 9));
// s == "The date is 2012-12-9"
template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value>::type fmt::print(std::basic_ostream<fmt::char_t<S>> &os, const S &format_str, const Args&... 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 S, typename ...Args>
std::enable_if<internal::is_string<S>::value, int>::type fmt::printf(const S &format_str, const Args&... args)

Prints formatted data to stdout.

Example:

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

template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value, int>::type fmt::fprintf(std::FILE *f, const S &format, const Args&... args)

Prints formatted data to the file f.

Example:

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

template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value, int>::type fmt::fprintf(std::basic_ostream<fmt::char_t<S>> &os, const S &format_str, const Args&... args)

Prints formatted data to the stream os.

Example:

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

template<typename S, typename ...Args>
std::enable_if<internal::is_string<S>::value, std::basic_string<fmt::char_t<S>>>::type fmt::sprintf(const S &format, const Args&... args)

Formats arguments and returns the result as a string.

Example:

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