我有一个标题,它为我的自定义类型定义了所有 {fmt} 格式化程序。
为了缩短编译时间,我想减少这个自定义格式化程序头文件的依赖关系,并决定将所有格式化程序定义为外部模板,其中实现放在 .cpp
中。 , 头文件中的声明如下:
template<>
struct formatter<MyType> : formatter<std::string>
{
auto format(const MyType& t, format_context& ctx);
};
extern template struct formatter<MyType>;
...以及 .cpp
中的定义文件:auto formatter<MyType>::format(const MyType& t, format_context& ctx)
{
return format_to(ctx.out, "MyType: {}", ...);
}
主要优点是头文件变得不那么重,所有自定义类型都可以向前声明,并且我不再包含世界,以防我想在某个翻译单元中使用单个类型的自定义格式。但是,大多数关于使用 {fmt} 实现自定义格式化程序的示例都定义了
format()
函数作为模板化在 format_context
上的模板函数类型:template<typename FormatContext>
auto format(const MyType& t, FormatContext& ctx);
这不适用于外部模板,因为我需要声明 format()
适用于所有可能类型的 FormatContext
前面。这很容易出错。目前,仅使用 fmt::format_context
工作,编译器会告诉我它何时不再足够。我想知道如果没有在
FormatContext
上模板化格式函数,我会失去什么类型?在什么情况下是fmt::format_context
不够?有没有更好的方法来定义这些自定义类型格式化程序而不必将完整的实现放在头文件中?我正在考虑去std::ostream
路线,然后简单地包括 <fmt/ostream.h>
每当我想用 {fmt} 格式化我的类型时,但它首先部分地违背了使用 {fmt} 的目的。
最佳答案
what I loose by not having a format function templatized on the FormatContext type?
您将无法通过输出迭代器进行格式化。
以前这意味着您将无法使用
format_to[_n]
.然而在当前master
这个限制有已被删除,并且两者都是
format_to
和 format_to_n
与format_context
.现在只有format string
compilation可能需要自定义输出迭代器。
关于c++ - 带有外部模板的自定义类型 {fmt} 格式化程序,有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63075693/