1

Does template generated code become part of file that includes the header containing template class? Is it because template is not a code itself so there's nothing to export?

code_guri
  • 25
  • 7
  • 2
    Not exactly a duplicate, but do have a look at [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – mindriot May 04 '16 at 07:54

1 Answers1

2

Yes, the code generated by a template is instantiated where it is used. Similar to an inline function.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • In case of inline function whole function code is substituted at place where function is called, to avoid function call while executing code. Please explain how similar thing happen in case of template class ? – code_guri May 06 '16 at 07:47
  • In the case of a template class, it needs to be instantiated where it is used for any given type. Meaning if you compile 10 source files to 10 object files, you could get 10 instantiations of a template class for a single type. The linker can collapse them. Or you can do it explicitly by telling your compiler not to instantiate templates, and then you can write "explicit template instantiations" using `extern template` in one special source file. Almost no one does this. – John Zwinck May 06 '16 at 13:01
  • Thanks john, what you said makes perfect sense. I just want to clarify,that template class is substituted by preprocessor at place where we #include the header file containing template class, and than compiler generates the templated code there ? And if thats the case its not similar to inline function, right ? – code_guri May 07 '16 at 09:02
  • The compiler only generates the code when and where you instantiate it with a type. #including a header file doesn't instantiate templates. For example `vector` isn't instantiated until the point where it is used. – John Zwinck May 07 '16 at 12:36