So I was wondering where to put what when defining a template. As when the compiler instantiates a template the definition has to be present. It cannot be in another source file. Now this isn't an issue in small programs I'm currently writing but what if I were working on something big? Wouldn't there be multiple definitions of the template class/es. Wouldn't that decrease performance or does the compiler have a way of handling this?
So lets say you have a header file and you have your template defined there. You then include that in many, many files. That would result in a decrease in performance right? Because each object file has to have the definition in it.
I'm probably getting this over my head, there is probably an easy explanation for this. I have searched google and the only work around is to define the template explicitly in a header. Which isn't something you can do all the time.
So does the compiler work this out somehow, if so how? or I'm I just missing something?
Wouldn't there be multiple definitions of the template class/es.
A template class is not created unless used, but when used every instance generates code for it's use inline.
So lets say you have a header file and you have your template defined there. You then include that in many, many files. That would result in a decrease in performance right? Because each object file has to have the definition in it.
Not necessarily a decrease in performance, but perhaps an increase in compile time. The definition of a template class doesn't produce code, the declaration of an instance of the class is what triggers the generation of the code.
@jlb So what if I were to have many source files using Template<int> would that define one instance of the a class or will each source file have its own one?
Sorry just a newbie and don't get how the compiler will handle this.
Since templates are expanded inline you will have the template code everywhere it is used. Which means that if you have multiple instances of the class in the same file you will have multiple instances of the code in that file.
But note this won't necessarily cause a decrease in performance, quite often you will see an increase in performance, at the cost of an increase in executable size.
Okay that clears it all up, just read up on explicit instantiation and that seems to fix the increased executable size. Thank you again really appreciate it!