正常
std::format (C++20)
In a nutshell
A type-safe printf alternative—format strings with {} placeholders, compile-time checking of the argument count, and support for formatting custom types.
Header file
#include <format>
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Format a string | string format(fmt, args...) | Returns the formatted string |
| Format to output | void vformat_to(out_it, fmt, args) | Outputs to an iterator |
| Format to buffer | format_to_n(out, n, fmt, args...) | writes into a fixed buffer, returns the output end and the total needed length |
| Format to stdout | (C++23) void print(fmt, args...) | Writes directly to standard output |
| Positional arguments | "{0} {1} {0}" | References arguments by index |
| Width/precision | "{:>10.2f}" | Right-aligned, width 10, precision 2 |
| Custom formatting | template<> struct formatter<T> | Specialize std::formatter to support custom types |
Minimal Example
C++
// Standard: C++20
#include <format>
#include <iostream>
#include <string>
int main() {
std::string s = std::format("Hello, {}!", "world");
std::cout << s << "\n"; // Hello, world!
int version = 2;
double pi = 3.14159265;
std::cout << std::format("v{}. pi={:.2f}", version, pi) << "\n";
// v2. pi=3.14
// Positional arguments
std::cout << std::format("{0} + {0} = {1}", 3, 6) << "\n";
// 3 + 3 = 6
}Embedded Suitability: Medium
- Replaces
printf, eliminating the risk of runtime crashes from a format string that does not match the argument types - Replaces
std::stringstream, avoiding heap allocation overhead - Checks the argument count at compile time, but full compile-time validation of format specifiers requires the help of mandatory compile-time checking of format strings (C++23, P2216)
- Flash overhead can be significant (the code size of the formatting engine); evaluate before use on extremely resource-constrained devices
- The {fmt} library can serve as a fallback option from C++11 onward
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 13 | 17 | 19.29 |
See Also
Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0