如何让fmt::print传入空char*指针时不抛出异常?
如何让fmt::print兼容空char*并输出提示而非抛出异常?
问题重现
示例代码:
const char* abc = nullptr; printf("%s\n", abc); fmt::printf("%s\n", abc); fmt::print("{}\n", abc);
运行输出:
(null) (null) terminate called after throwing an instance of 'fmt::v9::format_error' what(): string pointer is null Aborted (core dumped)
可见fmt::print会对空char*指针抛出异常,而printf和fmt::printf则会输出(null)提示。针对项目中fmt::print调用量极大、不想全部替换的场景,可通过以下方法解决:
解决方案:自定义const char*类型的格式化器
通过特化fmt库的formatter模板,为const char*类型添加空指针处理逻辑,无需修改现有代码即可让fmt::print自动兼容空指针。
示例代码:
#include <fmt/format.h> // 特化const char*的格式化器 template <> struct fmt::formatter<const char*> : fmt::formatter<std::string_view> { template <typename FormatContext> auto format(const char* s, FormatContext& ctx) { // 空指针替换为"(null)"输出 if (s == nullptr) { return fmt::formatter<std::string_view>::format("(null)", ctx); } // 非空指针按正常字符串逻辑处理 return fmt::formatter<std::string_view>::format(std::string_view(s), ctx); } }; int main() { const char* null_ptr = nullptr; fmt::print("空指针输出:{}\n", null_ptr); // 输出:空指针输出:(null) const char* normal_str = "测试字符串"; fmt::print("正常字符串输出:{}\n", normal_str); // 输出:正常字符串输出:测试字符串 }
原理说明
fmt库支持自定义类型的格式化逻辑,通过特化fmt::formatter<const char*>,我们覆盖了默认的格式化行为:
- 当传入的
const char*为空指针时,主动替换为"(null)"字符串进行格式化 - 非空指针则沿用
std::string_view的格式化逻辑,保证原有正常字符串的输出不受影响
这种方法全局生效,所有现有fmt::print调用无需修改,直接兼容空char*指针。
内容的提问来源于stack exchange,提问作者yhz
相关产品推荐
相关产品推荐

