Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
josuttis_nm_c20_the_complete_guide.pdf
Скачиваний:
48
Добавлен:
27.03.2023
Размер:
5.85 Mб
Скачать

342

Chapter 10: Formatted Output

int main()

{

for (auto val : {Color::red, Color::green, Color::blue, Color{13}}) {

// use user-provided formatter for enum Color:

std::cout << std::format("Color {:_>8} has value {:02}\n", val, static_cast<int>(val));

} }

 

The program has the following output:

Color _____red has value 00

Color ___green has value 01

Color ____blue has value 02

Color _Color13 has value 13

This approach usually works fine if you do not introduce your own format specifiers. If only string literals are used as possible values, you could even use the formatter for std::string_view instead.

10.7Afternotes

Formatted output was first proposed by Victor Zverovich and Lee Howes in http://wg21.link/p0645r0. The finally accepted wording was formulated by Victor Zverovich in http://wg21.link/p0645r10.

After C++20 was standardized, several fixes against C++20 were accepted. The most important was that format strings are checked and must be known at compile time, as formulated by Victor Zverovich in http://wg21.link/p2216r3. Others are http://wg21.link/p2372r3 (fixing locale handling of chrono formatters) and http://wg21.link/p2418r2 (format arguments become universal/forwarding references).