You have to put all of your class template into your header file for it to work properly.
Why does a class template behave differently from a class? There's a good reason: because it's not a class. It's sorta a level above a class. It actually represents a family of (nearly identical) classes.
As an example, consider the vector class template. vector is not a type. vector<int> is a type; vector<Foo> is a type; vector<vector<char> > is a type. These types are called instantiations of vector, and are essentially classes. (I'm not sure if they're technically considered classes or not, but there's no harm in thinking of them that way).
As long as you don't try to make any instantiations of vector, the template generates no code whatsoever. As soon as you try to make a vector<int>, the compiler basically has to go find the vector template and generate code for a new "class" vector<int>. When you try to make a vector<float>, it has to do it again. Since it has to generate the entire class on the fly, the implementation of the functions must be present in the translation unit (i.e. in the source file that wants to use a vector<int>). This is opposed to non-template classes, where you already wrote the code for its functions, and they're in a different source file (translation unit). In that case, you can compile both (or all) source files separately and link your object files together later.
Now, the C++ standard says that there's supposed to be a keyword "export" that essentially allows separate compilation of templates (i.e. you'd use the export specifier before a template in its header file, then be able to have the implementation in a different file). However, no compiler to date (November 22, 2002) supports this keyword*, since there's really no way for the compiler to go out and "guess" which file has the implementation. Several compilers have alternate support for separate compilation.
The above also applies to function templates.
* Now (September 25, 2003) some compilers are starting to implement the export keyword, but it seems it might be causing more trouble than it's worth. We'll see...
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.