c++模板和头文件
所以,我听说 C++ 模板不应该分为头文件 (.h) 和源文件 (.cpp).
So, I heard that C++ templates shouldn't be separated into a header (.h) and source (.cpp) files.
例如,这样的模板:
template <class T>
class J
{
T something;
};
这是真的吗?为什么会这样?
Is this true? Why is it so?
如果因此我必须将声明和实现放在同一个文件中,我应该将它放在 .h 文件还是 .cpp 文件中?
If because of that I'm gonna have to put both declaration and implementation in the same file, should I put it in a .h file or a .cpp file?
推荐答案
Headers.
这是因为模板是在编译时而不是链接时实例化的,并且不同的翻译单元(大致相当于您的 .cpp
文件)仅在链接时相互了解".标头往往在编译时被广泛了解",因为您在任何需要它们的翻译单元中#include
它们.
It's because templates are instantiated at compile-time, not link-time, and different translation units (roughly equivalent to your .cpp
files) only "know about" each other at link-time. Headers tend to be widely "known about" at compile-time because you #include
them in any translation unit that needs them.
阅读 https://isocpp.org/wiki/faq/templates 了解更多信息.
Read https://isocpp.org/wiki/faq/templates for more.
相关文章