Christof Warlich wrote:
Greg wrote:
The definition of a template must be visible at the point it is needed
in a source file. In this case, the doSomething() method is needed in
main.cc, but its definition is not visible to main.cc.
But that's my point: If the definition _has_ to be visible in main.cc,
why does only the linker and not already the compiler flag an error?
A referenced template has to be visible in order to be instantiated -
and every referenced template must be instantiated in order for the
program to link.
Strictly speaking, a template class or function does not need to be
instantiated in the same translation unit that uses it - just as long
as the template is instantiated in at least one of the other
translation units that are linked together to produce the final
program.
But there are notable disadvantages if the template is not instantiated
in the source file the requires it. Consider:
* Added bookkeeping overhead
Instead of the compiler instantiating templates as they are needed, the
programmer has to assume the tedious responsibility of determining
which templates need to be instantiated and to maintain this list
during development.
* Potential code bloat
A programmer is likely to instantiate an entire class template for a
particular type instead of just the method or methods actually
referenced.
* Lost optimization opportunities
With the template definition not present at the point it is needed, the
compiler loses the ability to inline function calls or to perform any
other optimization with the template.at the translation unit level.
Greg