The following code example is taken from the book
C++20 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2021
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <iostream>
#include <string>
#include <format>
struct Value {
double amount = 0;
int precision = 2;
std::string unit = "Dollar";
};
int main()
{
Value v1{100}; // OK
Value v2{.amount = 100, .unit = "Euro"}; // OK
Value v3{.precision = 8, .unit = "$"}; // OK
Value v4{100, .unit = "Euro"}; // ERROR: all or none designated
Value v5{.unit = "$", .amount = 20}; // ERROR: invalid order
Value v6(.amount = 29.9, .unit = "Euro"); // ERROR: only supported for curly braces
for (Value val : {v1, v2, v3}) {
std::cout << std::format("{:.{}f} {}\n", val.amount, val.precision, val.unit);
}
}