This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Help with templates


Hi Ricardo,

> But why do I have to include a .cpp? Cpp's aren't linked??? I am a C  guy,
that's a little confusing.

>From a C perspective, think of templates as being analogous to #define.

What would happen if you did this in these files...

---- foo.h ----
/* Forward declaration */
#define foo
---- end-of-file ----

---- foo.cpp ----
#define foo 120
---- end-of-file ----

---- main.cpp ----
#include "foo.h"
int main() { return foo; }
---- end-of-file ----

You'd probably say, "That's not going to work!"  And you're right.

Same with templates!

Templates are much like IN-LANGUAGE (instead of the PREPROCESSOR-BASED)
definitions.  The part that is "macro'd" in is the template type parameters.

As such, the compiler needs to have the whole template (i.e., "macro") in
hand to expand it as needed.

Before you stress that the template, which can be quite hefty, is going to
be replicated in every object file (and it is going to be replicated in
every object file!), the linker is designed to strip out duplicates of the
template so the final executable (or shared library or whatever) will only
have one copy of the INSTANTIATED template.

By "INSTANTIATED template", I mean that foo<int> will be a different
instantiation from foo<char>, and that foo<int>'s code will not be reduced
from foo<char>.  (Sidenote, there are some templating tricks that allows
foo<char*> and foo<int*> to both reduce... but that's for the Stepanov's of
the world to figure out.)  However, 50 instances of foo<int> will get
reduced down to one instance of foo<int> in the final executable.

The above caveat about templates being fully in header files, is also true
about inline functions.  Inline functions should also be fully specified in
the header file in C++.  But inline functions don't "reduce", since they are
inline, as you would expect with a macro-function #define.  Sometimes a
function tagged as inline cannot be inlined by the compiler, so in that case
multiple copies of the the ersatz inline function will reduce in the final
executable.

NOTE:  I'm glossing over a lot of details.  I just want you to get the gist
of the template animal in C++, from a C perspective.

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]