Wednesday, 9 November 2016

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)?


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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...