On Mon, Feb 02, 2004 at 02:21:39PM +0100, Laurens wrote:
> Do templates have any significant impact on heap memory usage for instance? > Code size? Any caveats I should be aware of?
A C++ template is just an automatic way of generating code that is mostly repetitive, but just with different parameters. Think of it as a really powerful macro utility. When you declare a vector<int>, behind the scenes, C++ is basically creating a new class named "vector_of_int", generating code for that class based on the template declaration, and compiling it and adding it to the object file. You could do the same thing using some kind of preprocessor for a language that doesn't support templates.
Once you understand that, it should be plain that the biggest implication is code bloat. If you use a template with a three different classes in your program (e.g., vector<char>, vector<int>, vector<FormType*>, etc.), you are essentially creating 3 new classes, and all of the code for each of these "classes" is added to your application.
The problem is somewhat worse than this: the code for all these vector operations is declared *in line*, and is generated in line except insofar as a compiler decides not to do so. And if you look at the (impenetrable) header files that define the container classes, you'll see that they have some quite complex code that calls other, utility template classes, whose code is *also* declared in-line. An expert on the particular compiler (like, one of its implementers) would be the best source of information on how much actually gets inlined. Writing test progrmas and seeing how the .prc file size varies as template-using code is added is another approach.
Greg Lutz
NearSpace, Inc.
-- For information on using the Palm Developer Forums, or to unsubscribe, please see http://www.palmos.com/dev/support/forums/