Hello everyone, I am Hai Di!
In C++ development, string formatting is a frequent and easily overlooked requirement. Traditional methods such as <span>sprintf</span>
pose risks of buffer overflow, while <span>iostream</span>
has poor performance and cumbersome syntax. The fmt library, with its three main features of type safety, zero-cost abstraction, and minimal syntax, has become the cornerstone of C++20 standard formatting, garnering over 20k stars on GitHub and being widely used by major companies like Microsoft and Google.
Whether you need to handle high-performance logging, build network protocols, or simply beautify console output, fmt can bring a qualitative leap in development efficiency with a 5-minute learning curve. The API design significantly enhances code readability, while its performance, close to low-level operations, is an added bonus. Still using outdated formatting methods? It’s time to experience the true charm of modern C++!
1. Overview of Core Advantages of the fmt Library
- Type Safety: Compile-time checks for formatting parameters, completely eliminating
<span>%d</span>
and variable type mismatch segment faults. - Performance Boost: 5-10 times faster than
<span>sprintf</span>
and over 10 times faster than<span>iostream</span>
([official benchmark]) - Elegant Syntax: Python-style formatting syntax, supporting positional parameters, named parameters, and other advanced features.
- Cross-Platform: Supports C++11 and above, compatible with Windows/Linux/macOS.
- Strong Extensibility: Easily implement formatting output for custom types.
2. From Hello World to Practical Use: Complete Code Example Analysis
1. Basic Usage: More Concise than cout
#include <fmt/core.h>
int main() {
// Format string
std::string s = fmt::format("The answer is {}", 42);
fmt::print("{}: {:.2f}\n", "PI", 3.1415926);
// Direct output to stream
fmt::print(std::cerr, "Error: {}\n", "file not found");
return 0;
}
Output:
PI: 3.14
Error: file not found
2. Advanced Usage: Custom Type Formatting
#include <fmt/format.h>
struct Point {double x, y; };
template <>
struct fmt::formatter<Point> {
auto parse(format_parse_context& ctx) { return ctx.begin(); }
auto format(const Point& p, format_context& ctx) const {
return format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
int main() {
Point p{3.14, 2.718};
fmt::print("Point coordinates: {}\n", p); // Output: Point coordinates: (3.1, 2.7)
return 0;
}
3. Performance Optimization Techniques
// Compile-time format string check (C++20)
auto s = fmt::format(FMT_STRING("{:d}"), "42"); // Compile error: type mismatch
// Reuse positional parameters
fmt::print("{1} {0} {1}", "a", "b"); // Output: b a b
// Precompiled format string
constexpr auto fmt_str = fmt::compile<int>("{:04d}");
std::string s = fmt::format(fmt_str, 42); // Output "0042"
3. Six Typical Use Cases Recommended
- High-Performance Logging System
#define LOG_ERROR(...) fmt::print(stderr, "[ERROR] {}:{} | ", __FILE__, __LINE__); \
fmt::print(stderr, __VA_ARGS__)
LOG_ERROR("Connection timeout ({}ms), retrying...\n", 5000);
- Configuration File Generation
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf),
"[Database]\n"
"host = {}\n"
"port = {}\n"
"timeout = {:.1f}s\n",
"localhost", 3306, 0.5);
std::string config(buf.data(), buf.size());
- Protocol Message Assembly
struct Packet {
uint32_t seq;
std::string payload;
};
std::string build_packet(const Packet& p) {
return fmt::format("{:08X}{:04X}{}",
p.seq,
p.payload.size(),
p.payload);
}
- Unit Test Assertion Beautification
#define ASSERT_EQ(a, b) CHECK((a) == (b)) << fmt::format("Expected {}, got {}", (a), (b))
- Cross-Platform UI Development
// Generate HTML snippet
fmt::print("<div class='{}' style='color:#{:06X}'>{}<div>",
"warning", 0xFF0000, "Alert!");
- Numerical Processing and Conversion
// Readability handling for large numbers
fmt::print("{:.2e}", 123456789); // 1.23e+08
fmt::print("{:#x}", 255); // 0xff
fmt::print("{:₿>10}", 1.5); // ₿₿₿₿₿₿1.5
4. Perfect Compatibility with the Standard Library
Starting from C++20, the standard library <span><format></span>
header is designed based on the fmt library. Existing projects can migrate smoothly:
// C++20 standard mode
#include <format>
using std::format;
// Compatibility mode (supports C++11)
#define FMT_HEADER_ONLY
#include <fmt/format.h>
using fmt::format;
5. Performance Comparison Test Data
Testing formatting one million times with <span>"The value is {}"</span>
:
- fmt::format: 38ms
- std::stringstream: 420ms
- sprintf: 85ms
In terms of memory allocation, fmt reduces over 60% of memory operations through small string optimization (SSO).
Many students are preparing for campus recruitment but struggle to present impressive projects. For the project part of interviews, we have launched the C++ Project Practical Camp, which not only provides systematic learning of advanced C++ foundational knowledge but also allows you to choose a practical project to build from scratch. Instructors review code, provide guidance, and offer a wealth of learning materials for lifetime access.
Interested friends can add ↓↓↓
Conventional technical learning only improves coding skills, but does not enhance the ability to manage projects and solve problems from 0 to 1!
The training camp will guide you from 0 to 1 in C++ projects (you can choose any project from the project pool), helping you improve your project management skills and familiarize yourself with the complete project process, such as development environment, compilation scripts, architecture design, framework setup, code release, problem debugging, unit testing.
You will need to perform requirement analysis, project planning, architecture design, task breakdown, time planning, version management and many other tasks.
Additionally, you will inevitably encounter various problems during the project, which can gradually enhance your debugging skills, problem analysis abilities, and mastery of more debugging techniques.
When faced with tricky issues, dedicated instructors will provide answers and specific suggestions.
The projects in the project pool are completed by the instructor team after spending a lot of time, and they not only include complete code with clear comments, detailed documentation, and videos, but also have dedicated project instructor support, so you don’t have to worry about not being able to learn.
Trust me, these projects will definitely help you make significant progress! Below are the documentation for three of the projects.
