0

I'm looking to write a generic class (like this: template <Class T>) in C++11 but I was told that the implementation could only be written in the .h file, why is that?

I wrote some code (1000 lines) and it's a complete mess, I don't know where some pieces of code went. Is there any way to separate implementation and declaration?

  • 1
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – yaodav Jun 13 '20 at 19:09
  • The upvoted answer in the dupe shows how to do what you want with `.tpp` files. – cigien Jun 13 '20 at 19:18

1 Answers1

1

Well, no*.

To use any piece of code a translation unit needs to either compile it oneself or have access to a compiled version. One cannot compile all possible versions of a template class thus to use it a full definition is required.

.* Technically, if your class template will be used only for a couple of types then you could hide implementation in a .cpp and build all required versions in the same .cpp but it wouldn't be truely generic.

If you aren't happy with messy implementation you could hopefully implement the messy part in non-generic functions and hide those in a .cpp. Or, like in many header-only libraries, make namespace details or something and push all the "implementation" details there.

ALX23z
  • 4,456
  • 1
  • 11
  • 18
  • regarding 'details' how that will help make things more ordered? –  Jun 13 '20 at 19:22
  • @smith normally in open source libraries `details` implies that "do not use as it we might change it at any point of time". For your own projects you can hide various stuff in `details` that help you implement the templete and at the same time you signal others that they shouldn't be bothered with the namespace. For instance, you could make three completely different template classes dedicated to different template parameters in `details` and outside provide a single alias that alters between the class templates depending on the template parameters. – ALX23z Jun 13 '20 at 20:06