正常
std::format (C++20)
TL;DR
A type-safe printf alternative—format strings using {} placeholders, checks argument count at compile time, and supports custom type formatting.
Header
<format>
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Format string | std::format(fmt, args...) | Returns formatted string |
| Format to output | std::format_to(out, fmt, args...) | Outputs to iterator |
| Format to buffer | std::formatted_size(fmt, args...) | Pre-calculates output length |
| Format to stdout | (C++23) std::print(fmt, args...) | Outputs directly to standard output |
| Positional args | std::format("{0} {1}", a, b) | References arguments by index |
| Width/precision | std::format("{:>10.2}", v) | Right-aligned, width 10, precision 2 |
| Custom formatting | template<> struct formatter<T> | Specialize formatter to support custom types |
Minimal Example
cpp
#include <format>
#include <iostream>
#include <string>
int main() {
// Basic replacement
std::string s = std::format("The answer is {}.", 42);
// s == "The answer is 42."
// Alignment and width
int x = 42;
std::cout << std::format("{:>10}", x) << '\n'; // " 42"
// Type-specific formatting (hex)
std::cout << std::format("{:#x}", 255) << '\n'; // "0xff"
}Embedded Applicability: Medium
- Replaces
printf, eliminating runtime crash risks from mismatched format strings and argument types. - Replaces
std::stringstream, avoiding heap allocation overhead. - Checks argument count at compile time, but full compile-time validation of format specifiers requires
std::formatin C++23. - Flash overhead may be significant (formatting engine code size); evaluate for resource-constrained devices.
- The {fmt} library can be used as a backport for C++11 and later.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 13 | 17 | 19.29 |
See Also
Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0