是否有理由在标题中保留完全专用的模板?

Are there reasons for keeping fully specialized template in the header?

本文关键字:专用 有理由 标题 保留 是否      更新时间:2023-10-16

如果我有一个完全专门的模板函数,例如:

// This stay in the header
template<typename X>
void foo(x b);
// This goes into the source file - any drawbacks?
template<>
void foo(Bar b) {
...
}

是否有理由将其保留在标题而不是源文件中?我想将它们保留在源文件中,以减少编译时间(这些专用函数可能会变得非常大,并且它们在标头中拉取了很多依赖项(,但我想知道将它们放入源文件是否有任何权衡。

对于完全专用的模板,声明仍然应该在标头中(因此编译器知道它不使用主模板(:

template<> void foo(Bar b);

但是定义可以放在 cpp 文件中(或保留在标头中(:

template<>
void foo(Bar b) {
//...
}