Skip to main content
gamedev.net
🔒 Locked

c++ templates

Started by -=Code=- Nov 30, 2001 at 12:27 AM 0 replies 250+ views
Original Post
-=Code=-
-=Code=-
I''ve been reading up on templates for c++ and something is puzzling. Why does all the code go into the header file when using templates for binary trees, linked list etc.? I tried putting the code into the .cpp file as static lib but on linking I get an error. Anyone shed some light on this?
Fruny
Fruny
Quick answer : because current compilers do not support the ''export'' keyword that would let you do just that.

Longer answer : It is more or less the same reasons as why you need to put both the code of inline functions and declaration of class member variables in header files.
When you instanciate a template, the compiler needs to find the code it has to adapt to the required specialization. When the compiler processes file A (which includes header H), it doesn''t know anything about the code in file B. Remember that variables have to be declared extern to tell the compiler that they exist, somewhere else, and will be resolved at link time. Function prototypes create the same kind of placeholders.
But when you use a template, you need the code NOW, because you''re going to ''fill the holes'' left by the template parameters. Same as for inline functions, same as for information on the size of a class (hence the member variables).
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.