C++20 和 C++23 新特性:允许大幅改变 C++编程方式,提供了一些有趣示例。
- fmt 库集成:方便优雅地格式化字符串,其受 Python 等语言启发。
打印向量示例:
- 打印整数向量
v:std::println("{}", v); - 居中打印并加下划线:
std::println("{:\_^40}", v); - 逆序打印:
std::println("{}", v | std::views::reverse); - 打印最大值:
std::println("{}", std::ranges::max(v));
- 打印整数向量
- 打印多种信息:如打印名字、当前时间及名字,利用索引打印参数。
- 模板函数折叠示例:通过折叠实现灵活处理多个参数并进行相同操作。
- 除法函数示例:使用
std::expected处理除法,避免除零异常。 其他示例:
- 打印整数二进制及 trailing 0 位数:
std::println("{:b} {}", 4u, std::countr_zero(4u)); - 整数左移位:
std::println("{:x}", std::rotl(0xf0f0f0f0u, 4)); - 打印浮点数二进制:
std::println("{:b}", std::bit_cast<uint64_t>(1.0)); - 打印文件大小:
std::println("{} bytes", std::filesystem::file_size("demo.cpp")); - 写入日志并包含源代码位置:
auto log = [] (std::string_view message, std::source_location loc) { std::println("{} {}:{} function name: {}", message, loc.file_name(), loc.line(), loc.function_name()); }; log("problem", std::source_location::current());
- 打印整数二进制及 trailing 0 位数:
- 参考资料:可在 GitHub 查看完整示例[https://github.com/lemire/Cod...],推荐 Marius Bancila 的新书了解更多。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。