Catch up on stories from the past week (and beyond) at the Slashdot story archive


Forgot your password?
Programming Books Media Software Book Reviews IT Technology

C++ Templates: The Complete Guide 450

nellardo writes "The book C++ Templates: The Complete Guide, by Vandevoorde and Josuttis, Addison-Wesley 2003, is an authoritative treatment of exactly what it claims: the template mechanism of C++. If you are a C++ programmer, you should have this book on your shelf. If you aren't a C++ programmer, move along -- this book is highly specific to C++, and won't be much help in understanding the template mechanisms of other languages. Of course, if you aren't a C++ programmer, you probably wouldn't even give this book a second glance in the first place." Read on for the rest of Brook's review.
C++ Templates: The Complete Guide
author David Vandevoorde & Nicolai M. Josuttis
pages 528
publisher Addison Wesley
rating 10 for C++ programmers, 0 for anyone else.
reviewer Brook Conner
ISBN 0201734842
summary A thorough, exhaustively complete treatment of a complex subject. An essential reference for C++ programmers and a lengthy and boring book for anyone else.

The C++ programming language is widely regarded as a good systems programming language, albeit a complex one fraught with low-level details and issues (though arguably this is what makes it good for certain kinds of systems programming). For perhaps a decade now, C++ has had a template mechanism - in programming language circles, it might more properly be called a form of parametric polymorphism. The template mechanism, like many other forms of parametric polymorphism, is potentially extremely powerful, but the complexity of C++ makes it tough to thoroughly master. That's where this book comes in.

Most likely, an experienced C++ programmer has at least used templates. If nothing else, use of the Standard Template Library (or STL) requires at least knowledge of how to use templates. If you use C++ enough to care about templates, you probably know what they are, at least roughly, and if you don't, this isn't the book from which to learn about them. It very clearly requires (and explicitly states in the introduction) that you need to know C++ before making effective use of the book.

Designing template classes, however, is another kettle of fish, and if you're in a position where you're building template classes for someone else to use, you probably need this book. Unless, like the book's authors, you moderate comp.lang.c++.moderated. If you are such a super C++ guru, you may still find this book useful - it is a truly stupendous catalog of the capabilities and subtleties of C++ templates. If nothing else, you'll find examples for well nigh every use to which you are likely to put C++ templates.

The book's strengths, then, are its authoritative and exhaustive detail. On the downside, its examples are dry and flavorless. Perhaps this is intentional, as a way to suggest how some feature can be used in a variety of situations. I prefer a combination of specific, concrete examples, followed by a generic example. The specifics motivate the need for a capability, while the generic showcases the broad, interrelated aspects of the capability. The authors didn't follow that approach. I would suspect this comes in part from their mutual roles in C++ standards bodies - a specific example could be seen as too limiting, and so were left out.

Another drawback, to my thinking, is its resolute focus on C++ to the exclusion of all other languages. Don't get me wrong - I read the title, and it's a C++ book, so I don't expect it to teach me Scheme, much less Haskell. However, I think the complexities of C++ templates might have been easier to tackle and understand with at least pointers to other ways it could have been (and has been) done. If nothing else, citations of alternative approaches would be a useful source for the motivated reader. As it is, it doesn't even deal with differences between C++ implementations - it doesn't even list GCC in the index.

All in all, though, C++ Templates: The Complete Guide is exactly what it claims to be. It's an in-depth treatment of C++ templates and how they work. It isn't a cookbook for practical applications, nor is it a guide to further in-depth exploration of parametric polymorphism. But it is definitely a handy reference for the working C++ programmer to have on her shelf. If you're a working C++ programmer, I'd recommend it. If you aren't, you might want to pass on this one.

You can purchase C++ Templates: The Complete Guide from Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

This discussion has been archived. No new comments can be posted.

C++ Templates: The Complete Guide

Comments Filter:
  • by Anonymous Coward on Friday March 21, 2003 @11:48AM (#5565100)
    Oh, how I long for the day when men were men, and programmers actually understood how memory management worked. :P
    • by Anonymous Coward on Friday March 21, 2003 @12:01PM (#5565219)
      Oh, how I long for the day when men were men, and programmers actually understood how memory management worked. :P

      Memory management works???? :-P

  • Bloat (Score:2, Insightful)

    by warmcat ( 3545 )
    I have used C+ for several years, and love its abilities to model layers of belongingness with its OO principles: but I assessed templates as evil and have never used them. My understanding is that the template mechanism is like a super #define, that is, the compiler spawns multiple implementations of templated classes.

    The seemed to me a recipe for bloat/cache thrashing/ugliness. I did not see bloat addressed in the review. In my reactionary way I continue to believe my prejudices.

    Does anyone who has u
    • Re:Bloat (Score:5, Insightful)

      by Buck2 ( 50253 ) on Friday March 21, 2003 @12:00PM (#5565202) Homepage
      I'm just throwing this out there but anyone that knows any better please feel free to present an argument:

      We use the blitz++ library in our laboratory due to benchmark findings that it is an extraordinarily fast package of matrix-type operations. It has been repeatedly argued that the speed of the library is due to the fact that it is entirely (I believe) implemented with templates.

      If you'd like to read some hairy code ... check out blitz++. :) And the errors you can get when compiling are simply astounding. AFAICT, though, it's damn fast.

      So, no, templates don't necessarily lead to bloating/ugliness/slowdowns/whatever if done properly.
      • Re:Bloat (Score:4, Interesting)

        by Malc ( 1751 ) on Friday March 21, 2003 @12:04PM (#5565251)
        "If you'd like to read some hairy code ... check out blitz++. :) And the errors you can get when compiling are simply astounding."

        That is my biggest complaint with templates. Compilation errors can be horrendous, especially as they often appear far from point where you've made the error. My second biggest complaint are the debugger symbols that get produced for templates.
    • Re:Bloat (Score:4, Insightful)

      by Malc ( 1751 ) on Friday March 21, 2003 @12:01PM (#5565215)
      I use templates with virtually every class and method I write: the STL. I couldn't live without it. It simplifies my development efforts, and helps me produce C++ solutions faster and with greater reliability. So far none of the applications have needed performance tuning. I'm sure there are situations where it is in appropriate, just not in my circles. I shudder when I think back to my C++ days prior to using the STL. So, I'm all for it and the ditching of the pre-processor and basing things on void*.
    • Only when misused (Score:2, Insightful)

      by DreadSpoon ( 653424 )
      Templates are only bloat when misused. In many cases, your options are to write a template, or cut-and-paste then modify a class/function over and over. You can also write classes that only have template members, so if most of a class is the exact same no matter the data type, you're fine. Templates also let you do things you simply can't do in this low level of a language otherwise (and many high level languages also don't allow) - take a look at what the BOOST library does. There comes a point when y
    • by Chemisor ( 97276 ) on Friday March 21, 2003 @12:14PM (#5565351)
      Just like macros can bloat your code, so can templates. If you put "real" code in templates, it will be duplicated; however, consider that you would have probably had to write it anyway, and having template instances is FAR better than having cut-n-paste code. STL instances can get pretty big because they have lots of memory management code in there and type-specific operations; this is good because it gives you type safety and proper element assignments. You can implement it another way, but you have to sacrifice something. Either it is type safety (like Java does with its containers), or correct element handling (escuse the shameless plug for my own ustl [] library).
    • Re:Bloat (Score:3, Interesting)

      by jkujawa ( 56195 )
      You cannot use C++ effectively and safely without templates.

      The STL, especially, makes C++ an order of magnitude more usable and powerful.
    • Re:Bloat (Score:4, Redundant)

      by Waffle Iron ( 339739 ) on Friday March 21, 2003 @12:28PM (#5565496)
      The seemed to me a recipe for bloat/cache thrashing/ugliness.

      No, templates are often anti-bloat. With a good optimizing compiler, a dizzying heirarchy of layers of abstraction can often compile down to 2 or 3 machine opcodes. If you understand how to use STL properly (which includes double-checking your results by disassembling critical points in the binary and inspecting them) you can often get code that is almost as fast as hand-coded assembly. I think that in general, if you use the other main approach to abstraction in C++ (virtual method calls), it's harder for the compiler to crush all of the layers of abstraction down to zero.

      The main problem with C++ templates IMO is that they feel "brittle". It's hard to create large modular programs because of C++ #include dependencies and binary interface difficulties. I think that the best approach for large programs is to identify the performance-critical pieces and code them up in C++/STL as native modules for a nice high-level language like Python, then use the high-level language to glue everything together.

    • Re:Bloat (Score:5, Informative)

      by vidarh ( 309115 ) <> on Friday March 21, 2003 @12:28PM (#5565499) Homepage Journal
      If you're a C++ programmer and don't use templates, you're not doing your job. If you've ever used map,vector,multimap,set,multiset,list,string,pair or most other classes from the C++ standard library, you've been using templates (yes, even "string" - string is a typedef for std::basic_string).

      You're also being left behind in the dust. Modern C++ is all about exploiting templates to simplify development, and even reduce code bloat (by making it easier to reuse common code) and increase performance (through automatic compile time generation of heavily inlined versions of algorithms).

      If you make a huge template with lots of code that could be easily generalized for all types, then you're writing a bad template: You should factor all common code into a base class and make a template that contain the few parts of the code that are type specific. On the other hand, if your code can't easily be generalized for the types you need, templates save you the tedious and error prone task of maintaining multiple versions of your code specialized for multiple types.

      In that respect templates dramatically reduce the amount of work you need to do, if applied properly.

      As mentioned above, template techniques can dramatically improve performance over a generic algorithm by providing you with an automated way of generating heavily optimized inlined versions of an algorithm. The C++ template syntax is not really ideal for this, but the benefits from using templates for this are tremendous enough to make it worthwhile. Do a search for Vandevoorde's work on expression templates, or for Alexander Alexandrescu on Google to find more, or read Alexandrescu's articles in CUJ [].

      Continue to believe your prejudices if you want, but consider that if you can't use or write templates you've essentially shut yourself out of a huge segment of the C++ development job market. I would certainly never hire a "C++ developer" that don't at the very least have thorough experience with the STL, and preferrably understand how to write (and when to write) templates.

      • Re:Bloat (Score:3, Insightful)

        by warmcat ( 3545 )
        If you're a C++ programmer and don't use templates, you're not doing your job.
        I would certainly never hire a "C++ developer" that don't at the very least have thorough experience with the STL, and preferrably understand how to write (and when to write) templates

        As it happens most of my work is done down near the hardware. So those peksy issues of the relationship of compiled code to the hardware - which cut directly across things like having 24 copies of each method in a class because the class is

        • Re:Bloat (Score:5, Interesting)

          by vidarh ( 309115 ) <> on Friday March 21, 2003 @01:27PM (#5566096) Homepage Journal
          Either the function is generic, in which case, as I wrote, you should write your template properly by using a common base class containing the generic functions, and you won't have 24 copies, you will have one, and your runtime overhead of templating the class (I'm assuming a class, since templating a single function that is already generic enough to cover the types you need is meaningless) both in terms of space and time is exactly nothing - or the function is specific to the types in question, in which case the choice isn't between 24 copies or 1, but between a template or 24 hand written copies.

          Doing work near the hardware is no excuse not to use templates. On the contrary, I'd say that when you work on extremely performance critical code there is one thing you don't want your developers to do: reinventing the wheel over and over for non trivial parts of code - reinventing the wheel is something that's all too often done badly. A well written template will allow you to reuse well written, well tested efficient and small code over and over again for different types and different conditions without that risk.

          Another reason to use templates in an embedded system is that it allow you to easily write reusable components that can be adapted to a particular situation at compile time instead of runtime, opening up reuse opportunities across projects that would otherwise be difficult. This is often done with traits classes or policy classes that allow you to turn on and off functionality of a template at compile time, leaving out any code that isn't actually used.

          In fact, this is an important property of templates in C++: Code that isn't used isn't even semantically analysed, and certainly not included in the generated executable, while the same is not true for members of any class that is externally visible. So you might actually reduce your code size merely by changing some classes into templates even if they don't depend on any type parameter.

          Oh, and I've worked on embedded systems, using exactly the above techniques, including one platform that had 4MB flash and 4MB RAM that we ran Linux on together with FTP and SNMP servers that I wrote (in C++) as well as various other application code, a shell, etc., so I am familiar with how to make C++ code small, and that is one of the reasons I love templates.

    • Templates reduce code bloat. They allow you to write code once and use it across multiple types. That is, vector and vector are the same piece of code compiled twice. You only write it once. Granted, this makes a larger binary, but would you rather have 2x as much source or binary?


    • The seemed to me a recipe for bloat/cache thrashing/ugliness.

      Not when used properly. It should be mentioned, however, that early implementations in a number of compilers tended to create object code for identical template instances in multiple places (basically treating templates like your "super #define"). This really did_ lead to a great deal of bloat.

      Modern compilers (at least the ones I use) instantiate templates more intelligently. The only real problem I've seen is that templates, like a lot of u

    • They seemed to me a recipe for bloat/cache thrashing/ugliness.

      You have an excellent point. There's a subset of C++ called Embedded C++ [] that removes templates, multiple inheritance, new-style casts, exceptions, and some other features. Those are features that tend to make C++ programs bigger and slower than C programs. By limiting the features used by a program and its libraries, and Embedded C++ compiler is able to make leaner, faster code. This can be a huge benefit in embedded systems, hence the name.

      • Re:Bloat (Score:3, Insightful)

        Removing parts of the library might be a good idea (IOStreams, for example, is pretty slow, for example), and may be desirable in some cases, but the language features you mentioned should not affect performance. One of the design principles (not always kept, mind you) of C++ is that you don't pay for what you don't use.

        If you don't use multiple inheritance, then you don't suffer a performance drop. If you don't use exceptions, you don't suffer a performance drop. Templates, namespaces, and new-style c

    • You're right that templates can lead to object code bloat; if you used a templated container and specialized it for five different types, then five lumps of object code would be compiled.

      On the other hand, each specialization could be fast and memory-efficient because the compiler knows the size of the objects being stored - none of this putting integers into and out of boxes at run time whenever you want to store them in a container, as happens in Java and in many implementations of more high-level langua
      • Re:Bloat (Score:3, Informative)

        by vidarh ( 309115 )
        Actually, the C++ standard specifically does NOT require all pointers to be the same size. One of the reasons for this is that not all hardware platforms allow you to directly address every single byte, so that for instance a char pointer might need a pointer to the word a character is contained in and an offset into the word, or similar. The C++ standard only guarantee that all pointers to the same type are the same size.
    • Does anyone who has used templates have anything to say about templates and bloat?

      You're right, using templates does cause bloat -- executables become bigger and compilation becomes slower. The upside is that when used properly, they make your code much less susceptible to bugs. Before templates, your options were either to make separate container classes for each data type, or make a single class that stores void pointers and downcast everything back to your type by hand. Either method is tedious and

    • by renehollan ( 138013 ) <> on Friday March 21, 2003 @01:27PM (#5566101) Homepage Journal
      Templates can certainly lead to code bloat: you're telling the compiler how to generate classes (and, by extention, member and non-member functions) that are parametrized by type.

      So, instead of void Sort(int array[], size_t count) { ... } to sort an array of ints, you have template <typename T> Sort(T array[], size_t count) { ... } and the means to define a function that can sort an array of anything, with complete type-safety. Naturally, this generates a Sort function for each kind of array of things you need to sort... hmmm, there's room for improvement, no?

      If you don't get the "there's room for improvement" part, and use templates to get nice type-specific varients of common functions, you will get code bloat, and that is one of the things that give templated-code a bad reputation. But, we're Slashdotters, we're smarter than that.

      Recalling our C days, we immediately code void Sort(void *array, size_t count, int (*compare)(void *, void *)){ ... } where we pass a generic array pointer, and an additional pointer to a function that knows how to compare generic elements -- the specific call will then be something like: Sort((void *)pFoo, count, (int (*)(void *, void *))FooCompare). Gee, where did all our typesafety go? [Java programmers who are otherwise typesafety puristis grind their teeth at this point].

      If you can imagine a generic implementation, you can combine the best of both approaches: hiding the type downcasting inside the generic templated definition:

      inline void template <typename T> Sort(T array[], size_t count)
      genericSort((void *)array, count, (int (*)(void *, void *)SortCompare<T>);

      and for every array of type T you need to sort, define a int SortCompare&ltT&gt(T *arg1, T *arg2). (You could, alternately still pass that function to the generic sort routine, if you had different comparison functions for the same types of data (say, case-sensitive and case-insensitive sorting, or lexicographic vs. ASCII text sorting, etc.).)

      Note the inline declaration. This lets a smart compiler code the call to the generic function inline, avoiding a double function call. In practice, if the only thing you are doing is some type casting, no additional code is generated.

      So, you still have the potentially dangerous downcasting, but you've encapsulated it inside a template definition, relieving the application programmer to have to worry about it. Does all this mean extra work? It sure looks that you have to come up with a generic implementation and then make a nice and pretty templated type-safe wrapper around it.

      This is true, and well worth the effort for code that has to be robust and easy to use, particularly by others. Library writers know this rule all too well.

      Of course, in a pinch, or when a generic implementation is not obvious, or known to be non-existent, or when a particulary implementation exists for some types of objects, you can punt and let the compiler generate multiple instances of type-safe code, without a generic back-end implementation, accepting the code bloat that results.

      In the end, it becomes a matter of compromise and wise design decisions. Unfortunately, with choice, comes the effort to chose, and to chose wisely. It is the unwise use of templates that leads to their sometimes ill-deserved "code bloat" reputation. One of the differences between the skilled and less-skilled programmer is the ability to make these choices correctly and quickly, leveraging the language features that let the corresponding design decisions be put into practice.

      Other related C++ topics would include the notions that "multiple inheritence leads to slow code," "exception handling and run-time type information have high overhead". Again, one has to weigh the advantages offered by these techinques against the skill needed to use them wisely, and the performance penalty paid. I'll let someone else chime in now.

    • Re:Bloat (Score:3, Informative)

      by ucblockhead ( 63650 )
      Templates are a pretty straightforward trade of space for speed. Given the cheapness of memory these days, that's not a bad trade.

      Though personally, I find little bloat to speak of. It has been literally a decade since I had to worry about memory size. (As opposed to worrying about speed literally yesterday.)

      The largest C++ project I'm working on write now is about 7,000 lines of code. It makes heavy use of both the STL and templates. It runs about 500k on disk and seems to take between one and t

  • by Anonymous Coward
    Is this another book in their Professional Computing Series?

    I've found several of them that I've read to be excellent references. They aren't textbooks, but they contain lots of information that is accessible and useable to people who write lots of code and want it to be understandable and maintainable.
  • by ( 637314 ) on Friday March 21, 2003 @11:55AM (#5565158) Homepage Journal
    I know a lot of people who are required, for their job, to write both Java and C++ code. Are templates really applicable to those developers? In other words when you switch back and forth between the two frequently do you resort to the lowest common denominators of the language instead of using more "advanced" aspects?

    My J-Developer friend was just telling me the other day how he longed for templates in Java.
  • by Anonymous Coward on Friday March 21, 2003 @11:56AM (#5565172)
    I'd rather wait for the Microsoft guide to buffer overflows.

    An 800 page book written by true professionals"
    • I'd rather wait for the Microsoft guide to buffer overflows.

      What makes the haxx0r3d and o\/\/n3d MS servers is that at one time Billy G. said one of the advantage of Windows over UNIX was that UNIX kept on having buffer overflows, and look at this Microsoft stuff thats so much better. This is back in some sendmail bug days, and before Windows was really a net target. Anyone else remember Trumpet Winsock?

      The one thing that scares me really is not the hacks we know about, but the ones we don't. Fuck Cod
  • The C++ programming language is widely regarded as a good systems programming language

    This alone makes the review suspect. It is a shame that anyone believe this. All I have seen from C/C++ is bloat at runtime and speed issues because programmers do not understand the under lying "cost" of the any function they call and too many functions (and sub-languages like fprint) to call.

    • It's a developer issue, not a language issue. You said it yourself: because programmers do not understand the under lying "cost". He also says it's "widely regarded" in a certain way, which it is, whether you agree or not.
    • You're right- it is important to understand your language and what the consequences are of using particular features.

      However, don't automatically assume that C++ is always slower than C. Sometimes the opposite is true because you can do some stuff at compile-time in C++ that C would normally do at run-time.

      The often quoted example is the sort routine in the C++ library verses qsort(?) in the standard C library. Both library calls take a comparison function as a parameter. However, because the C++ versio
      • "Modern C++" from Alexandrescu is a fairly incomprehensible book that for the most part won't compile on most current compilers.

        Be that as it may be, there are many invaluable lessons in that book. I would recommend "C++ Templates" from Vandevoorde and Josuttis before you even attempt Alexandrescu's book.
  • by fcrick ( 465682 ) on Friday March 21, 2003 @12:08PM (#5565303) Journal
    Microsoft just doesnt't compile them properly and it is very frustrating to all C++ programmers. Chances are, if you write C++ in the commercial world, your company has the very wise policy of making sure you stay roughly within the capabilities of the most popular compilers. This basically means you can use STL's vector, string, and list, and a pretty small collection of others. This, in my opinion, is a programmer's tragedy.

    Utility C++ templates allow it to create and use some amazing things. I personally rarely write anything but the most simple ones, but when I'm allowed, there are huge libraries of amazing template classes. I learned ML at some point, and I remember the wonder when I happened upon the tuple template class for c++. With the exception of the fact you are forced to carry the type around (as a typedef of course), it works exactly like an ML tuple, a tool I came to love in my short time with ML. Someone simply wrote the template, and it was in C++ too! (a tuple is like an STL pair, but has an arbitrary number of members, set on construction).

    Of course, even VC7 doesn't compile it. If you work at Microsoft in the Visual Studio area, PLEASE tell them to get standard compliant already! Yeah yeah templates can be slow to compile, but give us the option at least!
  • Being fresh out of college, we used linked lists like they were going out of style. When I began work, I found out they were! Using an STL template and container serves as a good replacement for linked lists and other annoying data structures. I rarely use arrays anymore, I would rather use a vector or map. my personal preference, maybe because I hated linked lists and malloc arrays we exhaustively used in college.
  • by biglig2 ( 89374 ) on Friday March 21, 2003 @12:13PM (#5565349) Homepage Journal
    Can I just point out that as well as people who don't program in C++, "C++ Templates: The Complete Guide" will also be of limited interest to those who can't read, as well as those who can but read only Cantonese, not English. It is of limited use for those looking for a guid on changing the timing belts in '98 Pintos, and as a guide to the wines of the Alsace region it is sadly lacking. Dr Aloquin Samovar reports from the Naval Hospital that the book is not suitable for use by transplant surgeons as a temporary heart.
  • by baxissimo ( 135512 ) on Friday March 21, 2003 @12:15PM (#5565366)
    As it is, it doesn't even deal with differences between C++ implementations - it doesn't even list GCC in the index.

    That's too bad, because 9 out of 10 times when I've had troubles with templates it's because of differences between C++ implementations. Beautiful, well thought out, intricate standards-compliant examples are useless if I can't actually get them to compile with my real-world compiler!

    The book I'm looking for is the one that gives me real-world recipes for getting around bone-headded compilers. For example, there are at least 3 different ways to declare templatized friend functions depending on the compiler. Only one is correct according to the standard, but the standard isn't worth a whole lot to me today if the compilers I'm stuck using don't follow it. And likewise, an advanced templates book isn't of much use to me today if the examples won't compile on my compilers.

  • by dsplat ( 73054 ) on Friday March 21, 2003 @12:15PM (#5565368)
    First, there are some significant errata (and a lot of minor typos). Get the errata list and the code for all of the examples from one of the authors at his website []. Second, some of these techniques depend on features that aren't yet available in many compilers. Don't expect them all to work yet. They do discuss that in the book.

    With that said, I'm not sure that I would have rated this book a 10, but it's close enough that I'm not arguing. It is not a light read, nor should it be. This book and Andrei Alexandrescu's Modern C++ Design [] have convinced me that C++ templates are much more powerful, useful and complex than I realized. In fact, if I hadn't read Alexandrescu's book first, I wouldn't have thought C++ Templates was missing anything. These two books should be on the shelf of anyone who wants to use the full power of templates.
  • by jackjumper ( 307961 ) on Friday March 21, 2003 @12:28PM (#5565491)
    IMHO, is that a book like this needs to exist. Templates are *way* too complicated for something that is supposed to reduce complication.

  • I rarely see this in template discussions but the thing I love about templates is the ability to do template "closures" for lazy evaluation whereby instead of returning the result of a function, you return an object which represents the application of the function to those arguements. This object then gets cast into the final resultant object.


    Lets say you are concatenating a bunch of strings. Normally, you would create the concatenation of two strings, then concatenate the third, etc. Depending upon y
  • about templates is why this doesn't work:

    /* Foo.h */
    template<class T>
    class Foo {
    T foo;
    T getFoo();

    /* Foo.cpp */
    #include "Foo.h"

    template<class T>
    Foo<T>::Foo(T t) {
    foo = t;

    template<class T>
    T Foo<T>::getFoo() {
    return foo;

    /* main.cpp */
    #include "Foo.h"

    int main(int argc, char *argv[]) {
    Foo<int> foo = Foo<int>(123);
    int i = foo.getFoo();

    return 0;

    $ g++ -c Foo.cpp main.cpp
    $ g++ -o test main.o Foo.o
    main.o(.text+0x1a): In func

    • I suggest you read the section "Template Instantiation" in the gcc info documentation. Basically you never get an int version of Foo instantiated, as the compiler has to see the definition and usage in the same compile. gcc currently can't go back and work out where the source code is for the template and recompile it for the type.

      You can get round this by putting the entire template definition in the header file, which may lead to massive code bloat if your linker doesn't combine all the multiple definiti
      • *nod*

        You can get round this by putting the entire template definition in the header file, which may lead to massive code bloat if your linker doesn't combine all the multiple definitions.

        That is essentially #include "Foo.cpp", which is insanely ugly. Come to think of it, it's been so long since I last tried to use that I cannot remember exactly what I was trying to do with it -- except that it would have made things a lot easier. :-)

        As far as I can recall (without getting into specifics), I had a limi
    • I notice you've put templated code in a .cpp file instead of putting it in the .h file. I always had to put all templated code in the .h file so the compiler can make the proper code generation. It looks like you'll need the compiler to do the code generation because the linker barfs when you ask it to do it.

      It's a real shame if this book doesn't explain implementation details like this!

    • by rudedog ( 7339 ) <> on Friday March 21, 2003 @12:53PM (#5565769) Homepage
      about templates is why this doesn't work:

      main.cpp has never seen the implementation detials of the Foo constructor or the getFoo method, because g++ compiles each compilation unit in isolation. Conversely, no real code actually got generated when g++ compiled Foo.cpp, because that didn't contain a particular instantiation of a template, only the generic template definition.

      The typical idiom is to put a '#include "Foo.cpp"' at the bottom of Foo.h. Then, when g++ compiles main.cpp, it will have seen the template's implementation in order to turn it into code.

      This actually is explained in the book in question (chapter 6, I think).

  • Despite C++ templates having been around for quite some time, development environments still haven't caught up.

    Debugging heavily templatized code is thoroughly nasty. Names are mangled beyond recognition for anyone not using a 500 column display or lots of scroll bars. Stepping through code in the debugger often yields senseless results -- you often cannot see the source for the instructions being generated without manually tracing through the headers and looking for every overload and template body declaration. Templates thorougly ambiguate linker symbols. Templates slow compiles to a crawl, often adding tens or hundreds of thousands of lines to every inclusion of a given header in order to define the types it uses. With subtly improper use, templates can bloat code size astronimically and create horrendous execution bloat.

    I don't know how many weeks I've lost to helping others debug or rewrite their code because they thought they would do something "clever" with templates and they ended up creating a maze. And bringing in third-party code with templatized interfaces has frequently required more time to debug and adapt than it would have taken to create the code anew.

    If you're going to use templates, stick to simple container classes for now. Anything else should be considered theoretical research until the tools catch up. Let me repeat: development tools HAVE NOT CAUGHT UP WITH C++ TEMPLATES. There is no debugger available which makes templates as transparent as normal code, inline functions or even #defines.

    And please save your first forray into templates for private projects. Don't inject your template experiments into code others are trying to use!

    • Spirit [] has to be seen []to be believed. Basically you contruct a parser which looks like normal extended Backus-Normal Form (EBNF) but the source you write is 100% C++ source code - not run through a preprocessor:

      struct calculator : public grammar<calculator> {
      template <typename ScannerT>
      struct definition {
      definition(calculator const& self) {
      expression = term
      >> *( ('+' >> term)[&do_add]
      | ('-' >> term)[&do_subt]
      term = factor
  • by pclminion ( 145572 ) on Friday March 21, 2003 @12:59PM (#5565831)
    Templates are a crutch. So are overloaded operators, overloaded functions, public vs. private data, etc. A crutch is simply something which makes it easier to accomplish a goal. A crutch, by itself, is not a bad thing.

    However, it's nearly always fatal to mistake a tool (in this case, templates) for an end in itself (a functioning, maintainable codebase). No programming technology, be it HLL in general, objects, inheritance, or even templates will replace the need to think intelligently and make sound engineering decisions. You cannot build a skyscraper without the proper knowledge, no matter how excellent your hammer is.

    The company I work for is among the few remaining who produce large-scale Windows products written entirely (ok, 99.9%) in C. My work is in a totally different world than the object oriented people, yet I still manage to accomplish everything an OO programmer could do. The secret here is not cute little language features, but discipline and correct design.

    IMHO, templates do not deserve a book quite this large. Clearly, the author has had enormous experience in various situations, and knows how to solve all kinds of problems with templates, BUT -- remember the famous words passed down from people wiser than ourselves: "When all you have is a hammer, everything starts to look like a nail." Make sure the hammer isn't the only thing in your toolbox.

  • by Lailyx ( 622440 )
    For those not too familiar with templates (personally I learned all from Stroustrup's book), there are a lot of interesting and sometimes quirky features.

    One of the best examples perhaps is the STL vector class, which has three implementations. An implementation for a vector of booleans (made specifically to save space), a vector for any type of pointer, and then the generic vector class that covers anything else. Templates have some powerful features.

    Unfortunately, there's still some things that need to
  • by CodeArt ( 540731 ) on Friday March 21, 2003 @01:14PM (#5565953)
    If you want to be able to recognize what is the truth and what are lies (more lies) with Sun's J2EE and Microsoft .NET proprietary frameworks (however, they have and will have place in computing) study Standard C++ with the STL. Just reading Bjarne Stroustrup's interviews you will avoid shortsightedness and you will learn much more about computing then reading anything else.
  • by IWannaBeAnAC ( 653701 ) on Friday March 21, 2003 @01:33PM (#5566162)
    I don't understand the comment about examples. In the early part of the book, it is true that many of the examples are rather generic, but adding another set of more concrete examples would bloat the book, and would be completely unncesessary IMHO. They are easy enough to understand as it is (with well thought-out identifier names etc.)

    Later in the book, on template metaprogramming etc, there are lots of concrete examples. Perhaps the reviewer didn't read that far?

    True, the book deals exclusively with C++. But contrary to what the reviewer states, it deals extensively with differences in C++ implementations. Whether or not one particular C++ compiler is listed in the index is not a very good judge!

    Reading his last paragraph, I am sure now the reviewer did not read all of the book. It is not written in "cookbook" style, but for sure everyone reading the book will learn and discover new ideas for template design that they didn't know before. And the capabilities of parametric polymorphism are explored in detail, with quite large sections on how they could be extended (and possibly will, in the next C++ standard) to make some types of programming easier.

    In short, this book is a mix between an academic treatise (it encapsulates practically all that is currently known about the C++ template mechanism), and practical guide to writing your own templates.

The solution of this problem is trivial and is left as an exercise for the reader.