简体   繁体   English

用C ++编译模板头

[英]Compiling template header in C++

I have a main.cpp and node.h(template) file. 我有一个main.cpp和node.h(template)文件。 It seems to work when I compile only main.cpp that includes node.h. 当我仅编译包含node.h的main.cpp时,它似乎可以工作。 I am wondering if it is okay not to compile node.h? 我想知道是否可以不编译node.h吗?

C++ compilers generally require that the definitions of all templates be visible in every translation unit in which they are used (the one real exception is if you only allow particular specializations to be used and those specializations are instantiated somewhere, in that particular instance you can get away with hiding the implementation). C ++编译器通常要求所有模板的定义在使用它们的每个翻译单元中都是可见的(一个真正的例外是,如果仅允许使用特定的专业化,并且这些专业化在某个地方实例化,则在该特定情况下,您可以获得隐藏实现)。

Whether you split template declarations from their definitions as you describe is really just a matter of style. 在描述时是否将模板声明从其定义中拆分出来,实际上仅是样式问题。 Personally I don't care for that as it makes it that much harder to find the actual code for any given template. 就我个人而言,我并不在乎,因为这使得找到任何给定模板的实际代码变得更加困难。

However if the code you are dealing with is large enough (as many boost libraries are, for example), then it may well make sense to implement the public template in terms of many private parts and it can well make sense to have those parts be split into their own headers. 但是,如果您要处理的代码足够大(例如,很多boost库都在其中),那么就可以从许多私有部分来实现公共模板就很有意义了,而让这些部分成为拆分成自己的标题。 But again, so long as all the needed code is available in every translation unit it is simply style and one choice is really not any "better" than another so long as it is consistent. 但是同样,只要在每个翻译单元中都可以使用所有需要的代码,它就是样式,只要选择是一致的,一个选择实际上就不会比另一个更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM