Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including .cpp file in the header file for a template class

Tags:

c++

templates

I do know that template class's definition and implementation should be on the same header file. But I was taught a bit differently at school.

I'll have the template class's definition in the header file, and at the end of the header file, I'll do #include "MyFile.cpp", which contains the implementation of the templated class.

Is this bad programming practice?

like image 897
dwnenr Avatar asked Aug 14 '15 07:08

dwnenr


People also ask

Do I include cpp file in header?

You should never include a cpp file ( or anything that is not a header ). If you want to compile a file, pass it to the compiler. If you both #include and compile a source file, you'll get multiple definition errors. When you #include a file, its contents are copied verbatim at the place of inclusion.

Why should templated code be implemented in a header file?

If these template class implementations were not in the header, they wouldn't be accessible and hence won't compile.

Do templates have to be in header files?

To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.


1 Answers

"Is this bad programming practice?"

In general not and it's a very common technique. But the problem is the .cpp file extension, that would affect many IDEs and build systems to consider it as a regular source file. More commonly used extensions are .tcc, .tpc.

like image 189
πάντα ῥεῖ Avatar answered Oct 11 '22 00:10

πάντα ῥεῖ