Thursday, 7 December 2017

Why do C++ template definitions need to be in the header?












e.g
when defining a template class why do the implementations of the class methods need to
be in the header? Why can't they be in a implementation file
(cpp/cxx)?


itemprop="text">
class="normal">Answer



A template
class is not a class, it's a template that can be used to create a
class. When you instantiate such a class, e.g.
MyTemplate, the compiler creates the class on the
spot. In order to create it, it has to see all the templated member functions (so that
it can use the templates to create actual member functions such as
MyTemplate::foo() ), and therefore these templated
member functions must be in the header.




If the members are not in the
header, the compiler will simply assume that they exist somewhere else and just create
actual function declarations from the templated function declarations, and this gives
you linker errors.



The "export" keyword is
supposed to fix this, but few compilers support it (I only know of
Comeau).



You can also explicitly instantiate
MyTemplate - then the compiler will create actual
member functions for MyTemplate when it compiles the
cpp files containing the MyTemplate member function definition
templates.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...