Is it advised to not to separate declaration and definition templated class functions.

Hi everyone :)

I have a query regarding use of templates for class member functions.
Usually we separate the member function declarations and definition in a .h and a .cpp file;

1) Is the same not advised for template class member function ?
2) If not advised, could you kindly provide some reference for what issues it
could create ?

Thanks for any kind of help :)
Last edited on
Lets put it this way. We have a program:
1
2
3
4
5
6
#include "Foo.h"

int main() {
  Foo<double> bar;
  bar.drink();
}


There is no concrete class Foo<double> (unless someone has written a specialization), but Foo.h has a template. The compiler will write constructor and destructor of Foo<double> based on that template and implement a Foo<double>::drink() too.

Why? Surely the implementations are in the object file created by compiler of Foo.cpp? Just link from there?
Alas, why should Foo.cpp know that Foo<double> is required? It does not. It has just template code.

Yes, it is the compilation of main() that does instantiation and thus has to see all the template code. All of the template has to come in with the #include "Foo.h".


The Foo.h could include the Foo.cpp. Then casual reader of Foo.h sees just the definition, not the implementation. Extension .cpp might not be appropriate, if one mentally associates it with "separately compiled source".
Thanks @keskiverto for this clear answer :)
@keskiverto
Great explanation!
Topic archived. No new replies allowed.