CP

fmtlib / std::format

Type-safe formatting with fmtlib and C++20 std::format conventions

Details

Language / Topic
cppC++
Category
Libraries

Rules

balanced
- Use `fmt::format("Hello, {}!", name)` or `std::format` (C++20) instead of `printf`/`sprintf` — format strings are type-safe and immune to format string vulnerabilities.
- Use `fmt::print` for direct output instead of `std::cout << ...` chains — it is faster, more readable, and avoids stream state issues.
- Use named arguments `fmt::format("{name}: {value}", fmt::arg("name", n), fmt::arg("value", v))` for clarity in complex format strings.
- Use `fmt::join(container, ", ")` to format ranges without manual loop-and-separator logic.
- Implement `fmt::formatter<T>` specializations for custom types to enable `fmt::format("{}", my_object)` — define `parse()` and `format()` methods.
- Use `fmt::format_to(std::back_inserter(buf), ...)` for zero-allocation formatting into pre-allocated buffers.
- Prefer `fmt::memory_buffer` over `std::string` for high-throughput formatting paths — it avoids repeated heap allocations.