Archived

This topic is now archived and is closed to further replies.

UberXenon

Template definitions in .cpp instead of .h

Recommended Posts

UberXenon    122
OK, here's the deal. Why do template classes (or is it class templates >_< ) have to have the function definitions in the .h files instead of in the .cpp files? Putting template class function definitions in a separate .cpp file causes unresolved external linker errors. Why is this? Is it some of the same reasons that inline functions have to be defined in the .h instead of the .cpp files? This is really annoying. Also, I'm thinking of buying "C++: The Standard Library" and wanted to get some opinions. I flipped thru it and what I saw I really liked. Anyone else who has this book want to comment on it? Edited by - UberXenon on 10/8/00 6:12:36 PM

Share this post


Link to post
Share on other sites
spock    217
Yes, I find that kind of annoying too, but there's a perfectly reasonable explanation. You can put definitions for specific instances of template functions in your .cpp files, but not actual templates. It is indeed kind of similar to the inline definition problem, and a limitation of the traditional separate compilation model rather than of C++ as such.

Think about it from the compiler's point of view: what kind of code would it generate for the module containing your template function definitions? It can't generate any code, because it does not know what template arguments to generate code for. Of course, it would not be able to generate the code while compiling modules using the templates, either - the function definitions are no longer visible there, remember?

You can make a development environment without these problems, but then you would have to make the compile and link operations more tightly integrated.

Edited by - spock on October 8, 2000 7:52:35 PM

Share this post


Link to post
Share on other sites