Advertisement

Template definitions in .cpp instead of .h

Started by October 08, 2000 06:08 PM
0 comments, last by UberXenon 24 years, 2 months ago
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
------------------------------------------------------------Four young warriors arrive, each holding an ORB...byrdjb@email.uah.edu
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

This topic is closed to new replies.

Advertisement