Hello,
C++ requires that the declaration and definition of a template must be in the same file.
Suppose we have the following scenario:
//tc.h
template<T>
class{
};
//file1.cc
#include"tc.h"
class<int> obj1;
bla bla .....
//file2.cc
#include"tc.h"
class<int> obj2;
bla bla ....
when file1.cc and file2.cc are complied separately, each of them will contain a realization of a template for int. I wonder how the linker handle this situation. The linker will leave two realizations in the final code(which will increase the size of the final code) or it will only keep one realization(which seems more complicated)
The linker is able to figure it out properly. However, FYI, C++0x introduces the "extern templates" capability which explicitly forces the compiler not to instantiate a template in a particular translation unit, and the linker will pull a definition from elsewhere if it exists. I believe Visual Studio and gcc both support this in their latest versions.
C++ requires that the declaration and definition of a template must be in the same file.
Not exactly. To be more accurate, it requires for the full definition to be visible in all translation units using the template. Or to be even more precise, it requires the definition of whatever is used in the translation unit.
This usually leads to designs where the header file contains the class definition, at the end of which, we include a ".inl" file, which will contain the definitions of all the functions.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks