Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why doesn't my template class compile when it's not all in the header?

Programming

Why doesn't my template class compile when it's not all in the header?

by  chipperMDW  Posted    (Edited  )
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...
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top