c ++模板和头文件 [英] c++ template and header files
问题描述
所以我听说c ++模板不应该分为.h和.cpp ...
so I heard that c++ templates shouldn't be separated into a .h and .cpp...
,例如一个这样的模板:
for instance a template like this:
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?
推荐答案
标题
这是因为模板在编译时被实例化,时间,而不是链接时间和不同的翻译单位(大致相当于您的 .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 了解更多信息。
这篇关于c ++模板和头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!