Ren said:
I have found that to use a template class, I need to include the .cpp
file for the linker to find the function. However, I only need to
include .h file for a regular class. Is this a VC limitation or is
this a known fact? Could someone shed some lights on this? Thank you.
VC++ implements what's known as the "inclusion model" of template
instantion. In fact, all C++ compilers except 1 (Comeau) implement only
this model.
Under the inclusion model, the compiler must be able to "see" the definition
of the template in every translation unit where it's used. This is because
a template is not executable code per-se (hence isn't linkable). Rather, a
template is a recipe that the compiler follows to create executable code
(which can be linked). This process of creating code is known as template
instantiation.
Typically template developers just put the entire template definition into
the .h file (and have no .cpp file), since nearly all compilers implement
only the inclusion model.
The C++ standard defines a second model, the "export model", based on the
"export" keyword. Under the export model, template defintions can be placed
anywhere, provided the template defintion is marked with the "export"
keyword. The compiler and linker then need to do the necessary bookeeping
to locate template definitions and create instantiations as they're needed.
The jury is still out on export - it's a very difficult feature for compiler
writers to implement. Nearly 6 years after approval of the C++ standard
there is now 1 complete implementation. As experience with this one
implementation grows, users will either pressure other vendors to implement
export, or decide that it's not worth it and stick with the inclusion model.
Time will tell.
For now, you have to include everything in the .h (directly or indirectly).
-cd