print("Hello World!");
什么?这不是Python,这是一个C++ 23的print
继C++ 20引入了std::format之后,C++ 23又引入了print。std::print的功能依旧与fmt::print的类似(参见std::print - cppreference.com和Overview — fmt 10.1.0 documentation)
到目前为止以下代码已经可以在最新版MSVC通过/std:c++latest参数编译(gcc 13.2.1和clang 16.0.6暂未通过测试)
#include <print>
int main(){
std::print("Hello World!\n");
}
什么?你说这和printf看着没区别?好吧,上述代码确实直接把print
改为printf
之后依旧可以实现相同功能
那么我们来看看print的真正用法
与Python的print不同,std::print或者fmt::print更像是输出format后的内容
来看看print的定义:
template< class... Args >
void print( std::FILE* stream,
std::format_string<Args...> fmt, Args&&... args );
template< class... Args >
void print( std::format_string<Args...> fmt, Args&&... args );
在cppreference中,对print函数的描述为”根据格式字符串 fmt
格式化 args
,并将结果打印到流中。“
听起来有点绕,那来看个例子(摘自cppreference)
#include <cstdio>
#include <filesystem>
#include <print>
int main()
{
std::print("{0} {2}{1}!\n", "Hello", 23, "C++"); // overload (1)
if (std::FILE* stream {std::fopen("test.txt", "w")})
{
std::print(stream, "File: {}", "test.txt"); // overload (2)
std::fclose(stream);
}
}
以上代码的终端输出为
Hello C++23!
同时,该程序会生成一个名为”test.txt“的文件,内容为
File: test.txt
相信在未来,std::print将会改变std::cout的垄断局面,C++ 23标准的提出也将会是对于C++语言的一次大变革,无论是好是坏,终究是多了一种选择
至于最后结果如何,那让我们拭目以待吧~