You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在编译时确定C++类型对应的printf格式说明符?

问题描述

其他格式化方法无法解决通用问题,必须使用printf格式字符串。

似乎应该有一种通过宏或constexpr实现该功能的简单方式:

int -> "d"
unsigned -> "u"
long -> "ld"
unsigned long -> "lu"
long long -> "lld"
unsigned long long -> "llu"

用于如下可移植代码:

std::chrono::milliseconds value{20};
char buffer[128];
std::snprintf(buffer, sizeof(buffer), "...%" FMT(std::chrono::milliseconds::rep) "...", value.rep());

C++20†或Boost库中是否有实现该功能的方案?


†我目前可用的工具链支持-std=c++20,但未提供std::format。此外,部分C库要求传入printf格式字符串作为参数。

内容的提问来源于stack exchange,提问作者OrangeDog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:12:33