Inclusion of header files in case of templates.

丶灬走出姿态 提交于 2019-12-20 03:31:38

问题


When we make a class we declare its functions in a header files and define them in a source file... then the header file can be included in the main file to use the class...

But if we declare a template class in header files and define it in the .cpp file and then if we include the header file in the main(containing int main) file then why does a linker error crop up... and the error does not crop up if we included the .cpp file(containing the header file ) in the main file... any answers plz?


回答1:


Templates don't actually produce any object code at the point where the compiler reads their source code; they're (typically) only "instantiated" when something actually uses the template. So if you define a template function in one source file, and call it from another, the code for the template function doesn't get compiled at all: it's not in the first object file since nothing there needed it, and it's not in the second object file since the compiler didn't have access to the function's definition.

You define template functions in header files so that in each translation unit where something calls the template function, the compiler has access to its code and can compile a copy of it specialized with the appropriate template arguments.

Alternatively, you can use explicit instantiation: you define the template function in a .cpp file, and also tell the compiler exactly which types that it should compile the function for. This is harder to maintain, because you have to keep track of which instantiations are needed by the rest of the program. If something calls foo<float>(), but you've only explicitly instantiated foo<int>() and foo<char>(), you get a missing-symbol error.

You shouldn't #include a .cpp file from another .cpp file. Just put the template function definitions in the header together with their declarations.




回答2:


A template is neither a class nor a function. Its a pattern that compiler uses to generate classes or functions.

Very nicely explained in HERE



来源:https://stackoverflow.com/questions/7584781/inclusion-of-header-files-in-case-of-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!