如何使用C ++ 20 std :: format? [英] How can I use C++20 std::format?

查看:609
本文介绍了如何使用C ++ 20 std :: format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 20引入了 std :: format 。与 printf std :: cout 相比,优点是什么?
我怎么使用它,有人给它举例?

C++20 introduces std::format. What are the advantages over printf or std::cout. How can I use it and someone give an example of it?

推荐答案


是printf

What are the advantages over printf

类型安全的优点。对于printf,程序员必须仔细将格式说明符与参数的类型匹配。如果他们输入有误,则该程序的行为是不确定的。这是一个非常常见的错误来源,尤其是对于初学者。

Type safety. For printf, the programmer must carefully match the format specifier to the type of the argument. If they make a mistake, the behaviour of the program is undefined. This is a very common source of bugs, especially for beginners.

为了公平起见,只要使用恒定格式的字符串(只要程序员已经记住/知道如何启用警告。无论如何,使用模板参数推导自动选择格式化的类型会更方便,更安全。

To be fair, decent compilers diagnose these mistakes as long as a constant format string is used, as long as the programmer has remembered / knows how to enable the warnings. Regardless, it is much more convenient, and safer to use template argument deduction to choose the formatted type automatically.

此外,无法扩展printf来支持打印类

Furthermore, there is no way to extend printf to support printing class types.


或std :: cout

or std::cout

流操纵器非常繁琐且冗长,并且行为不一致。一些操纵器是粘性的,影响所有后续插入,而其他操纵器仅影响单个插入。

Stream manipulators are quite cumbersome and verbose, and have inconsistent behaviour. Some manipulators are "sticky", affecting all subsequent insertions, while others only affect only a single insertion.

iostream API中的格式和参数之间缺乏分隔可以说很难理解(预期的)结果。

The lack of separation between the format and the arguments in the iostream API arguably makes it harder to comprehend the (intended) result.


如何使用它

How can I use it

要么等待编译器/标准库实现对其进行支持。
或者,如果不想等待,请使用原始非标准版本。然后按照文档进行操作。

Either wait for your compiler / standard library implementation to support it. Or if don't want to wait, use the original non-standard version instead. Then follow the documentation.

标准规范为 C ++标准。也有一些网站介绍了该标准,包括以更方便的格式的形式提供的库。 。另一个很好的信息来源是标准提案。非标准版本(在上一段中链接)的回购也有大量文档,尽管与标准版本有所不同。

The normative specification is the C++ standard. There are also websites that present the standard, including this library in a more convenient format. Another good source of information is the standard proposal. The repo for the non-standard version (linked in previous paragraph) also has tons of documentation, although there will be differences to what will be in the standard.


有人举个例子吗?

and someone give an example of it?

在这里,你去了(摘自libfmt的文档):

Here you go (adapted from the documentation of libfmt):

std::string s = std::format("I'd rather be {1} than {0}.", "right", "happy");

这篇关于如何使用C ++ 20 std :: format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆