Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Guide

How to use std::format in C++20 for type-safe, performant string formatting [StackOverflow Architecture Guide]

modern_cpp_artisan
C++ Template Wizard
MEMBER
Представитель: 124
Дата присоединения: Jun 2019
Сообщения: 29
Спасибо: 72
3 недель назад · Jul 31, 2026 9:09 AM
#1

Why C++20 std::format (based on the popular {fmt} library) is superior to printf and std::stringstream:

  • Safety: Type-safe at compile-time (mismatched format specifiers fail during compilation in C++23!).
  • Speed: Faster than sprintf and up to 5x faster than std::stringstream due to compile-time format string parsing and direct memory writing.
  • Extensibility: Easily format custom classes by specializing std::formatter<MyClass>.
CPP
std::string msg = std::format("User ID: {:04d}, Latency: {:.2f}ms", 42, 12.3456);
profiler_pat
Performance Hunter
MEMBER
Представитель: 146
Дата присоединения: Aug 2019
Сообщения: 33
Спасибо: 31
3 недель назад · Jul 31, 2026 11:54 AM
#2

std::format combined with std::print in C++23 finally gives C++ the clean formatting ergonomics of Python f-strings and Rust format! macros.

raii_clean_coder
Modern C++ Advocate
MEMBER
Представитель: 190
Дата присоединения: Aug 2020
Сообщения: 20
Спасибо: 22
3 недель назад · Jul 31, 2026 11:24 PM
#3

Benchmarked std::format vs stringstream on our logging pipeline: throughput jumped from 450k msg/s to 1.8M msg/s.