|
-
June 30th, 2009, 09:45 PM
#3
Re: unresolved externals with templates
Actually, it's not entirely true that function bodies of templates must be in the header files, or included in every CPP that uses the template.
This is a common misunderstanding. The importance of this technique isn't that strong anymore, but at one time compilers ran on machines with 64mbytes or less, it was paramount.
The technique is called explicit template instantiation. The linker must find an instantiation of the template matching all type uses of the template. That is, if you use the template on behalf of int and float types, there must be code generated on behalf of both types in at least one object file, so the linker will find them. (You could generate ints in one obj and floats in another, and I've even had to divide a collection of functions for each type in separate obj files, due to memory limitations of the compiler/system at the time - in the early to mid 90's, when 32 Mbytes of RAM was $1,000 - Mbytes, that's not a misprint).
In the "function body file(s)", you must list the explicit instantiations for each and every type you require. Instead of calling the this a "cpp" file, you might use a slightly uncommon extension "inl" - for inline - or "tpl" for template. This is the file that contains the function bodies for the templates.
You create a cpp to instantiate the types involved. Include the header and the "inl" file (you could do this at the tail of the cpp where you have the function bodies), then, issue this for each type:
template TClass< obj >;
where TClass is your template class, and obj is the type of the explicit instantiation.
This creates the code for the indicated type. List each type, and the code will exist in the given obj file for the linker to find.
Back in the day when this was new, Borland had a different syntax for the explicit template instantiation. The one I've listed here worked on GCC 3.x and Visual Studio from at least 2002, and I seem to recall VC6 and VC5 complied.
At one time, years ago, it was all too common for template code to overload the RAM availability during compilation. This technique was useful to localize the template code into various obj files, so as to minimize the impact of templates during compilation. In the current era this isn't all that important, but it can still be used.
Last edited by JVene; June 30th, 2009 at 09:57 PM.
If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|