简体   繁体   中英

Compiling template header in C++

I have a main.cpp and node.h(template) file. It seems to work when I compile only main.cpp that includes node.h. I am wondering if it is okay not to compile 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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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