Sunday 7 April 2019

c++ template and header files




So, I heard that C++ templates shouldn't be separated into a header (.h) and source (.cpp) files.



For instance, a template like this:




template 
class J
{
T something;
};


Is this true? Why is it so?



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?



Answer



Headers.



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.



Read https://isocpp.org/wiki/faq/templates for more.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...