5

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?

dwnenr
  • 443
  • 1
  • 4
  • 15
  • 1
    Nope, it's very common for implementations to do this although they tend to give a different suffix to make it clear it's not meant to be compiled separately like "tcc" in the case of GCC. – user657267 Aug 14 '15 at 07:07
  • It's just a convention issue. – songyuanyao Aug 14 '15 at 07:07
  • Thanks for the replies guys! – dwnenr Aug 14 '15 at 07:08
  • 1
    You just have to make sure that whatever build system you're using doesn't automatically try to compile the .cpp file. And include it within the include guards. – juanchopanza Aug 14 '15 at 07:08
  • It's a pointless slight of hand in my view. A cpp (or tcc) file included in a header is a header for all intents and purposes. Might as well do the straightforward thing and put all the code in a single file. – john Aug 14 '15 at 07:16
  • @john This may clutter readability of the header a lot. That's the reason why it's externed. – πάντα ῥεῖ Aug 14 '15 at 07:46

1 Answers1

5

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

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    +1 `.tcc`; There are so many ways software can mess up already, no sense using `.cpp` to confuse your build system when `.tcc` is common. – R2-Dequeue Aug 14 '15 at 07:48
  • I've also seen `.tpp` and `.inl`, the latter being used because `inline` functions deserve the same treatment. – Morwenn Aug 14 '15 at 08:40
  • @Morwenn There's not really a common convention, and I have seen a lot of different styles. The important point is to make it distinct from what is used by the build system to find regular c++ source files. – πάντα ῥεῖ Aug 14 '15 at 08:43