Slashdot Mirror


C++ Templates: The Complete Guide

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 bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

371 comments

  1. Are templates always necessary? by ChaoticChaos · · Score: 0, Interesting

    The only place I ever saw a good use for Templates is in the C++ Container Classes and that woudn't be necessary if all C++ objects were inherited from one object like Java's objects are.

    Templates only seem to be a necessary evil in OO languages that don't ultimately inherit all objects from one object.

    1. Re:Are templates always necessary? by tomhudson · · Score: 4, Insightful

      But then you loose the flexibility of multiple inheritance if everything ultimately has a single parent. It's always going to be a trade-off. If there was "one right way" to do everything, we'd all be out of jobs within the next decade :-)

    2. Re:Are templates always necessary? by syle · · Score: 2, Informative

      Hi, have you ever heard of the STL?

      --

      /syle

    3. Re:Are templates always necessary? by Anonymous Coward · · Score: 2, Informative

      Java's everything-inherits-from-Object model is annoying & sometimes rather ugly. There is a vocal group of Java programmers trying to add templates to Java, you should check it out before declaring templates an unnecessary evil.

    4. Re:Are templates always necessary? by FortKnox · · Score: 5, Insightful

      Well, I'm going against my grain here (being a Java lover), but templates mean that you ensure cast.

      For example, I make a stack in C++:
      Stack bleh<int> = new Stack();
      int i = 1;
      bleh.push( i );
      (excuse my syntax, I havne't C++'ed in a few years) and I have a stack full of ints.
      If i use a java container:
      Stack javaStack = new Stack();
      javaStack.push( new Integer( 12 ) );
      I lose cast. If I pop from C++'s bleh, I'm guaranteed to have an int. If I pop from Java's javaStack, I'm getting a java.lang.Object. I have to force cast and have a chance of a runtime exception.

      That is one major reason why templates are a good thing.

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    5. Re:Are templates always necessary? by J0ey4 · · Score: 5, Informative

      You are forgetting one of the biggest advantages to generics such as templates, speed. When templates are used much if not all of the binding is accomplished statically at compile time, when inheritance is used much if not all of the binding occurs at runtime. When you use inheritance every call to a virtual method requires a lookup to the vtable, this overhead is non-exsistent in templates. This is not an issue if you are writing bloated desktop apps in Java, but embedded or system-level applications demand the highest speeds possible.

    6. Re:Are templates always necessary? by TechnoVooDooDaddy · · Score: 5, Funny

      a fairly well thought out, educated, concise, relevant comment on the article..

      WHO ARE YOU AND WHAT HAVE YOU DONE WITH SLASHDOT!?

    7. Re:Are templates always necessary? by fredrik70 · · Score: 2, Interesting

      yeah, but then you would have to do all this awful casting everywhere as you have to do in Java. TEmplates is a much more elegant solution IMHO.
      Java is supposed to have templates from 1.5 anyway IIRC, so you'll have a choice then.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    8. Re:Are templates always necessary? by ChaoticChaos · · Score: 2

      A post like your's is the reason I posted. I wanted to see some varying opinions on the subjects. Thanks for falling into my trap. LOL!

      1) Why do you find Java's object model annoying/ugly?

      2) Why in the world would a group of Java programmers want Templates added to the language? It's easy to find out what Class an object is in Java. I never have typecasting issues.

    9. Re:Are templates always necessary? by Anonymous Coward · · Score: 1, Informative

      What idiot modded this down? It's a genuine question...

      Templates are great because you can program generically but take none of the speed hit of using inheritance and virtual function calls.

      Whereas in Java you get such abominations as an array of Integer objects, C++ templates allow you to have an array (or vector) of ints.

      In theory, Java's approach looks nicer. But then in theory Java should not have atomic types (int, byte etc) - and yet we're stuck with them for performance reasons. Templates are all about performance.

    10. Re:Are templates always necessary? by SquareOfS · · Score: 5, Informative
      Umm . . . not sure if we're missing the point here but:

      One of the major strengths of templates is to avoid exactly the situation that Java everything-from-Object inheritance causes in collections.

      In other words, this code:

      MyObject m = (MyObject)iterator.next();
      gets boring really quickly. Templates in collections saves you all that downcasting.

      In fact, it's so useful, it's appearing in Java in JDK1.5, courtesy of JSR 14.

      But far beyond convenience when typing, the important point is that using templates or generics in collections turns the typesafety of collections into a compile-time check rather than a runtime exception. Which is a Good Thing.

    11. Re:Are templates always necessary? by Politburo · · Score: 1

      If the only thing you're ever pushing on the stack is an Integer, then there is no risk of error from casting back to Integer when you pop off. To get an int then of course you can use Integer.intValue(). Slightly annoying and roundabout, but I've never had a casting problem when I always knew why type of data was going into the structure.

    12. Re:Are templates always necessary? by fredrik70 · · Score: 3, Informative

      check out this extension:

      http://www.cis.unisa.edu.au/~pizza/gj/

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    13. Re:Are templates always necessary? by FortKnox · · Score: 3, Informative

      I should have completed my thoughts before posting.
      I wanted to conclude that the only way to ensure cast with java's is either
      A.) Write a wrapper around the collection/map (where the accessors cast to the object, eg:
      public void setStack( Integer input )
      ).
      B.) Use arrays

      The big downfall of java.lang.Object is unsure cast (so you have to be careful with your coding, and follow good polymorphic code styles).

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    14. Re:Are templates always necessary? by lazyl · · Score: 3, Informative

      You imply that inheriting from a base class is always better, but that's not necessarially true.

      The guy(s) who wrote the STL Containter Classes did it that way (using templates) because they think it's better than having all the objects inherit from one base. It's a style of programming called Generic Programming.

      The basis of Java is dynamic run-time polymorphism. Using templates and generic programming techinques most run-time polymorphic algorithims can be reimplemented using compile-time polymorphism, which is much faster. That's what the C++ STL container classes are. That's where the power of templates are.

      p.s. I've looked at the book in the article and I would describe it as an entire book of special cases. It explains things like recursive template definitions. Things that are so confusing that I try and stay away from most of them. They make code un-readable to anyone but a template expert. Then again, I don't write templated libraries either.

      --
      Aw crap, ninjas!
    15. Re:Are templates always necessary? by fredrik70 · · Score: 1

      well, because they really want to perhaps? you're not the only java developer and taste differs.
      See this:
      http://jcp.org/en/jsr/detail?id=014

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    16. Re:Are templates always necessary? by Anonymous Coward · · Score: 0, Funny

      Linus good. Fuck SCO.

      More appropriately: SCO fuck Linus good.

    17. Re:Are templates always necessary? by FortKnox · · Score: 3, Interesting

      If the only thing you're ever pushing on the stack is an Integer, then there is no risk of error from casting back to Integer when you pop off.

      But you can't be absolutely sure. Yes, in practice, we generally assume everything is ok, and we rarely have trouble, but when you get down to reuse things can get hairy (hey, the compiler isn't stopping me from adding my String into the Stack, so why not?).
      The nice thing about Java to counter, though, is reflection. You can always check the class type and methods before casting.

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    18. Re:Are templates always necessary? by ChaoticChaos · · Score: 2, Interesting

      This ultimately comes down to a decision of *when* do you want to handle the "type" issue.

      In Templates, you decide up front.

      In Java, you handle the decision when you actually use the java.lang.Object object. In your example, adding the simple "if" check with the code ".getClass().getName().toLowerCase()" to determine you're truly using an Integer would eliminate any runtime errors whatsoever.

      I have never had a Java runtime error over typecasting issues. If something unexpected is in the Container, I throw an exception or bypass the value entirely. There is no excuse for having a typecasting issue in Java when you can check the object's type.

    19. Re:Are templates always necessary? by truth_revealed · · Score: 4, Insightful

      Templates only seem to be a necessary evil in OO languages that don't ultimately inherit all objects from one object.

      This is a naive view that circa 1992 C++ collection class designers used to share. The OO-container strategy was proven to be slow and not type-safe. The designer of the C++ Standard Template Library (STL) Stepanov does not even believe in OO programming - he calls OO a hoax. I personally would not go that far, but I appreciate that OO and generics are completely independent concepts. Furthermore, an STL map or vector working on types directly is much more space efficient than any OO container-based approach because each object contained does not require OO overhead. Indeed, native types (ints, doubles, etc) in vectors can be nearly as efficiently stored and accessed under STL as would C style arrays. No need for awkward casting or unnecessary and slow boxing/unboxing. To sumamrize, C++ templates and the STL fit in perfectly with the C++'s "zero overhead" principle.

    20. Re:Are templates always necessary? by ChaoticChaos · · Score: 1

      Thanks for the link. Please understand that I'm not refuting their decision to request Templates, I'm just wondering why they want it.

      I'll study the link you provided.

      Peace.

    21. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Cruft, much? Java objects have ancestry a mile long and waste gargantuan amounts of memory. The virtual CPU is also an inefficient piece of junk, which is something you'd expect more from a physical CPU whose design is fixed.

    22. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      It's inefficient and stupid.

    23. Re:Are templates always necessary? by FortKnox · · Score: 2, Interesting

      I already conceded this point somewhat in another reply.

      Its not that I always have trouble with it, its more when dealing with another persons code and reuse that you are never sure.

      BTW - Using "instanceof" is a lot easier than ".getClass().getName().toLowerCase()". Even easier would just be to catch the ClassCastException, report it (or swallow it), and go on (or get the next value).

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    24. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Those ifs and function calls cost processor cycles, bloat-whore.

    25. Re:Are templates always necessary? by Anonymous Coward · · Score: 0
      The OpenStep Foundation library uses Objective C, and kicks ass.


      Templates are more multipurpose though -- since they can be used with non-object types like int or char, and can be used as a typesafe #define.

    26. Re:Are templates always necessary? by Politburo · · Score: 1

      Feel free to write a better language yourself.

    27. Re:Are templates always necessary? by FortKnox · · Score: 1

      Why in the world would a group of Java programmers want Templates added to the language? It's easy to find out what Class an object is in Java. I never have typecasting issues.

      Again, I'm going against the grain. I'm a giant Java supporter, but your statement is rather arrogant.
      Why should they add garbage collection? I never have problems writing destructors!

      Perhaps you don't work in a large enterprise setting, but sometimes we have standards that require heavy typecasting, and the only good way to do that is passing around arrays (and GOD do I hate arrays when we have collections!). Templates would solve the issue by keeping a heavy typecast, but at the same time, keep collections. Everyone is happy! :-)

      Why do you find Java's object model annoying/ugly?

      Some people just hate java. Its either the object model, the speed (which isn't an issue anymore), or the 'memory bloat'. Ignore those comments, its just angry coders that aren't up to speed with java (or coded in it once when it was java1.1).

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    28. Re:Are templates always necessary? by Anonymous Coward · · Score: 1
      The nice thing about Java to counter, though, is reflection. You can always check the class type and methods before casting.
      So I have a collection (stack, hashtable, whatever) of Integers. I get one of them out, as an Object. I check its type...and it's not an Integer! What can I do? Nothing, really. I might as well throw an exception, because I sure as hell can't do anything meaningful here, because I only know how to deal with Integers coming out of my collection.

      Checking type and methods is a poor substitute for enforcing that only the correct things get put in the collection in the first place.
    29. Re:Are templates always necessary? by Anonymous Coward · · Score: 1, Insightful

      Exactly. If there is one thing Java lacks that is more strong typing in its Collections classes. The collections classes are arguably one of the best things that have happened to Java in a long time, but the fact that you have to use casting so often really leaves a bad taste. C++ templates definatelty rule in that area (coupled with operator over-riding, which I also think is super cool).

    30. Re:Are templates always necessary? by Anonymous Coward · · Score: 0
      In your example, adding the simple "if" check with the code ".getClass().getName().toLowerCase()" to determine you're truly using an Integer would eliminate any runtime errors whatsoever.
      Absolutely not! If you've designed this collection to store Integers and a non-Integer comes out of it at runtime, that's a runtime error! I don't care if you trap that error and swallow it or whatever, you have an error in your code because the wrong thing is being put in your collection.

      Never, never code like this. It's awful!
    31. Re:Are templates always necessary? by bunratty · · Score: 3, Informative

      GJ is the old implementation of Java Generics. It has since evolved into JSR-014. Sun has a prototype implementation of a compiler that supports generics, and there's even an entire forum for discussing Java generics.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    32. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      So why not just use arrays?

    33. Re:Are templates always necessary? by ChaoticChaos · · Score: 1

      I am not a C++/Template god like many of the /.ers are,,, but if I recall correctly, once you set the type for the templated class, that entire class can only accept that one type.

      I have constant need in Java to store all kinds of objects in Hashmaps. Templates would get in the way big time for me.

    34. Re:Are templates always necessary? by ChaoticChaos · · Score: 1

      I agree with you, but the concern being set forth by others is that because Java's Container Classes aren't templated, you can't tell what is being stored.

      I have to check the type being stored in my code because I have need to store a wide variety of objects in Hashmaps.

    35. Re:Are templates always necessary? by bunratty · · Score: 3, Informative
      The nice thing about Java to counter, though, is reflection. You can always check the class type and methods before casting.
      It's almost always better to avoid reflection than to use it. In this case, an instanceof test will be easier and faster. Example: Quick, write this code using reflection instead of instanceof:
      if (x instanceof Number) {
      Number n = (Number) x;
      // ...
      }
      Now time how much slower it is...
      --
      What a fool believes, he sees, no wise man has the power to reason away.
    36. Re:Are templates always necessary? by alyosha1 · · Score: 1

      This is one of the key strengths of C++. It provides two powerful abstraction mechanisms - runtime abstraction, throught the use of virtual functions, and compile time abstraction, through the use of generics (templates). The programmer can choose which mechanism is appropriate for the problem he is solving.

      One big advantage not mentioned yet is that using generics as an abstraction mechanism causes errors in your code to manifest themselves at compile time rather than runtime - i.e. on your desk rather than your client's !

    37. Re:Are templates always necessary? by fredrik70 · · Score: 1

      taste differs, what you might not like, many other people might find the dogs bollocks.
      Fails to see what would be such a 'necessary evil' thing with templates for c++, on the contrary, I find it much more elegant with templates.
      If you absolutely have to use a lib with a common base class in c++ you can always go and use MFC, they do just that.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    38. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      I agree, but in that case u can always revert to casting your objects to java.lang.Object.

      I am thinking more of the times when I need a collection of a particular type of object, but what Java has me do is add the objects as I would, but cast them on retreival. This has 2 drawbacks, firstly it makes for rather ugly looking code, and secondly, you are loosing compile time typechecking ... some one else's code might be adding the wrong type of object into the collection, and there would be no way of telling before you actually ran the code.

      I am not against casting per se, and I believe that it has a purpose, but I think that it is a concept that is basically being abused when you use Java's collections. It would certainly help if Java as a language were more strongly typed in this area.

    39. Re:Are templates always necessary? by kin_korn_karn · · Score: 1

      you should use perl, then you wouldn't have to worry about types at all :D

      (just kidding)

    40. Re:Are templates always necessary? by fredrik70 · · Score: 1

      Ah, looks like I'm sitting on old info, thanks for the link.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    41. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Well ... that would be fixing the wrong problem. Java is statically type (same as C++), where as perl is not. The problem is that Java is not as strongly types as some people (I) would like it, where as templates in C++ afford for stronger typing when you use containers, something that is clearly missing from Java's collections classes.

    42. Re:Are templates always necessary? by fredrik70 · · Score: 1
      I have constant need in Java to store all kinds of objects in Hashmaps. Templates would get in the way big time for me.



      in c++ this is done exactly as in java, it just that you have to explicitly set your common base class yourself, in java class Object is always there by default.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    43. Re:Are templates always necessary? by Leimy · · Score: 1

      Inheriting everything from "Object" isn't good enough either... which is why Java 1.5 will have templates as well.

      Often times you want the compiler to be able to do some type checking at compile time to make sure you can even call certain functions on certain objects.

      OOP is ok... but it can't solve all problems easily and refactoring of old OOP designs is a huge pain in the ass sometimes. This is why there are technologies like Aspect Oriented Programming in existence. AspectJ is a good example of this and I believe it is available with the popular eclipse IDE.

    44. Re:Are templates always necessary? by dabuk · · Score: 2, Informative

      There is no reason why you can't have multiple inheritance if everything inherits from a single base class.

      C++ might have problems because it would have to use virtual inheritance which probably hurt performance. Eiffel has a base class called ANY which is like Java's Object class. So you can declare lists like LIST[ANY] if you want, but it also has genericity allowing you to declare your list as LIST[INTEGER].

    45. Re:Are templates always necessary? by Ed+Avis · · Score: 1
      Templates only seem to be a necessary evil in OO languages that don't ultimately inherit all objects from one object.

      What, like Java? The most commonly used types in Java (int, bool, maybe float) don't inherit from Object.

      You can manually put them into wrapper objects like Integer which do inherit from Object, but you could equally well do that in C++ by defining a single Pointer class which wraps a pointer-to-void. But of course in C++ you wouldn't want to, because you can have type-safe containers without such shenanigans.

      --
      -- Ed Avis ed@membled.com
    46. Re:Are templates always necessary? by ives · · Score: 1

      For an excellent overview of generic programming in C++ and the STL in particular, check out Generic programming and the STL, written by Matthew H. Austern.

      It's definitely the best C++ book I've read so far.

    47. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      I'd like to add that templates are also about correctness. The type checking mechanism makes sure that I can only use types with the template that I meant to use with them, and no others. If the template can only take "generic object" then no such checks can take place.

    48. Re:Are templates always necessary? by robertchin · · Score: 1

      You can use class introspection in Java to find out its proper class, it's part of the polymorphism by dynamic binding of runtime procedures design of the VM.

      Or, you could use Objective-C, ala NeXTSTEP, where the generic pointer id always knows that the object type, and therefor never downcasts to the root object (Java was based in part on Objective-C). The nice thing about Objective-C is that unhandled exceptions aren't volatile (well, unless you end up trying derefrence a null pointer). In either case, yes, C++ templates are probably a great degree faster, but then again you loose all the dynamic features of a proper runtime system (so then you'd have to declare your methods virtual, which would end up causing your C++ app to run slower, but with the added pain of templates when you're using the STL).

      The worst part about Java is its masochistic typechecking system. It's got all of these nice runtime features, but the compile-time typechecker really stands in your way as far as accessing this backend power.

    49. Re:Are templates always necessary? by cushty · · Score: 1

      You forget (or have never seen) template methods. std::swap(a,b), for example, swaps the values of two 'things' and can be specialised to handle 'things' that need more work than the standard 'assign a to a temporary, assign b to a, assign the temporary to b' mentality. Templates are not just for classes but for methods too.

      (big apologies for the 'things' bit ... early evening ... long day ... brain tired!)

    50. Re:Are templates always necessary? by bunratty · · Score: 1
      And instanceof is also more powerful than ".getClass().getName().toLowerCase()". It can report whether the class is a subclass of the type you are expecting, not just the exact class. The cast will work in the subclass case, and this is exactly what instanceof tests. The corresponding reflection test would be even more complicated than the code shown.

      Anyway, if you want the exact class test, it's better to write "if(x.getClass()==Integer.class)" and compare Class objects instead of dealing with Strings. Either this code or the instanceof code will be more robust and faster than the original code.

      Exception handling is not the way to go to handle casting issues, unless it truly is an exceptional or unexpected condition that the cast will fail.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    51. Re:Are templates always necessary? by Anonymous Coward · · Score: 1, Insightful

      Typesafe Collections are a good thing, agreed. But are they a big deal? I can't recall a bug thats bit me in the past three years with the Java collection of Objects model but I recall vividly the pain of developin with C++ templates, the bloating in apps, slow builds, and painful debugging.

    52. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      You say that with templates you lose the dynamic features of a runtime system. Templates aren't there for runtime typing. That's what inheritance is for. Java has everything inherit from Object, so even unrelated items can be stored together.

      You ONLY have runtime typing in Java. In C++ you have both runtime typing via polymorphism and inheritance and static, compile-time typing via templates. You can combine them by storing pointers to a base class in your container and get the best of both worlds.

      Templates aren't the end-all, be-all of generic programming. You say that Java's containers are more powerful because of the run-time typing but that same power is available through other features of C++, namely inheritance (which is how Java does it anyway).

    53. Re:Are templates always necessary? by Minna+Kirai · · Score: 1

      a decision of *when* do you want to handle the "type" issue.

      Not just *when*, but also *who*. Or actually, *what*.

      With a mechanism like templates, type checking is accomplished by the compiler, not the programmer. That means no extra statements in the source to bulk up the code, no extra conditional checks at runtime to slow it down, and most importantly, no opportunity for a human programmer to forget some of the checks.

      That is the fundamental difference between a C++ STL vector, and a Java Vector which happens to only contain Integers.

      An additional problem with the Java Vector (and something that'll be fixed when templates are introduced in Java 1.5) is that it can't contain things which don't inherit from Object (like int and float).

      (Note that if a compiler is very smart, it is theoretically possible for both methods to be equally efficient at runtime. But that degree of optimization is rare even today- and depending on the class linking style, it may be impossible for the compiler to get all the data needed to optimize like that.)

    54. Re:Are templates always necessary? by n3k5 · · Score: 1
      But then you loose the flexibility of multiple inheritance
      Please explain why you can't have both multiple inheritance and a basic object type?
      --
      but what do i know, i'm just a model.
    55. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      One big advantage not mentioned yet is that using generics as an abstraction mechanism causes errors in your code to manifest themselves at compile time rather than runtime - i.e. on your desk rather than your client's !

      Why do you want all those errors on your desk? Major hassle, never get anything done. I just distribute the source only and get *no* errors on my desk!

    56. Re:Are templates always necessary? by IWannaBeAnAC · · Score: 1
      For sure. Actually, your sig encapsulates the advantages nicely:

      if (!signature) throw std::runtime_error("No sig!");

      The template version would give a compile-time error instead - type-safe and no need to to runtime error handling!

    57. Re:Are templates always necessary? by tomhudson · · Score: 1
      You can if you want and the language supports it, it's just that the most popular implementations of single-parent hierarchies (such as Delphi/Kylix) don't. My reply was in regards to the parent poster's comment stating

      quote:Templates only seem to be a necessary evil in OO languages that don't ultimately inherit all objects from one object.

      Multiple inheritance doesn't depend on all classes having a same base type. This gives you more flexibility in designing a set of classes. I should have made this clearer :-) Thanks for pointing this out so I could clarify it.

    58. Re:Are templates always necessary? by IWannaBeAnAC · · Score: 1
      Sure, once this happens an invariant has been broken somewhere and the behaviour of the program from this point on is likely completely undefined.

      The point is though, with templates the compiler would not have allowed you to add an object of incorrect type to the container in the first place.

    59. Re:Are templates always necessary? by goodvilhunting · · Score: 1


      Templates programming is great if you want to avoid dynamic memory allocations, as for example in real-time applications where dynamic memory allocations cause non-deterministic performance.


      At clemson university robotics group, we created a generic robot control platform based on exactly such advanced C++ concepts. Take a look:
      Robotic Platform]

    60. Re:Are templates always necessary? by IWannaBeAnAC · · Score: 1

      And I would add, the need to do lots of casting (as opposed to simply calling a virtual function on the base class object) is a sure sign of a screwed up design.

    61. Re:Are templates always necessary? by rsclient · · Score: 1

      Here's a simple way to do it in a language that's almost like Java: Stack mine = new Stack() /Object_must_be=Int; (the "/" means, "here are the qualifiers to the code I just wrote"). In this case, the /Object_must_be=Int means that everything going it, and everything coming out, must be an int. The generated code remains the same: it's just a compiler check; that check will fix most of the problems with the Java "Stack" (etc) classes that the original replier mentioned. "All" that has to be done is mark the object up a little. We know, in java, when a method is a general one because it takes in or passes back an Object, so we don't generally need to mark up our original class. And heck, in debug mode, it can even be a run-time check too; we can even make it a run time check all the time.

      --
      Want a sig like mine? Join ACM's SigSig today!
    62. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Also, java generics can only store object references, ie. pointers to objects. Pushing millions of small structs or basic datatypes will be quite a bit more efficient in C++ than Java.

    63. Re: Are templates always necessary? by netjeff · · Score: 2, Informative
      SquareOfS wrote:
      But far beyond convenience when typing, the important point is that using templates or generics in collections turns the typesafety of collections into a compile-time check rather than a runtime exception.

      Templates in C++ go much beyond typesafe collections. As an earlier poster commented, in technical circles it's referred to as "parametric polymorphism". For the layperson, you can think of it as a form of specialized code generation.

      The best example of how much bigger they are than typesafe collections is the use of templates for traits and policies. Take the classic reference counted smart pointer, which usually looks like this:

      SmartPtr<int> i_sp = new int(5);
      cout << *i_sp << endl;

      What about the question of whether SmartPtrs should be allowed to hold null pointers? Maybe in some case it's appropriate, but in others an exception should be thrown if it's attempted. Rather than having two different SmartPtr implementation, you add a new template parameters, the OwnershipPolicy type. The SmartPtr author than provides types like AssertCheckStrict and NoCheck. So then your code looks like this:

      SmartPtr<int, NoCheck> i_sp = new int(5);
      SmartPtr<int, AssertCheckStrict> j_sp new int(6);

      This example comes from Alexandrescu's Modern C++ Design, and his Loki framework.
    64. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Very well stated answer. If I wasn't an AC, I'd mod you up!

    65. Re:Are templates always necessary? by ucblockhead · · Score: 3, Insightful
      The difference becomes clear if you accidently try to push something else on the stack. If you try to push a string onto the STL stack, you get a compile error. If you try to do the same to the Java stack, you don't find out until runtime, when you do the cast.


      In other words, you better hope that your testing is good and that the bug that causes a string to get put on the stack doesn't only appear in a rare set of conditions.

      --
      The cake is a pie
    66. Re:Are templates always necessary? by chrisknoll · · Score: 1

      I've heard Templates used in multiple ways, one being parametric polymorphism, such that you have the following:

      List productList = new List;
      Product p = new Product();

      productList.add(p); // works
      p = productList.item(0); // works, notice no cast
      productList.add(new Object()); // compile time failure: add must pass a Product parameter

      The other way I've seen it used is to do 'loop-unwinding' where you have a loop that at compile time you know the iteration bounds, and it will remove the loop and duplicate the looped code for each iteration.

      In the Java space, 'templates' are not realy the goal, rather 'parametric polymorphism' is because it can lead to faster execution (no casts at runtime, although currently no implementation supports this because it would require bytecode changes, the current generics compiler just hides casts), and also more explicitly define what collection classes are declared to contain.

      A lot of people have argued that they have never created a collection object (like ArrayList) that they accidently put the wrong type into it (or maybe they've done it once _ever_.) However, if you are working with a service library that someone else wrote that returns collections of things, you have no way of knowning what the collections of things contain without referring to some documetnation. Parameterized types explicitly declare what the collection contains, so you have a tighter integration with what the code is doing and documentation. (everone here infavor of self-documenting code, raise your hand).

      -Chris

    67. Re: Are templates always necessary? by SquareOfS · · Score: 1
      The clarification is appreciated, I suppose, but I was never maintaining anything different. My point was that for the purposes of collections , which is the use of templates that the parent post was speaking to, the advantages of templates over everything-from-Object is largely compile-time typesafety.

      Also, a reference-counted smart pointer won't impress a Java coder such as the parent poster, since garbage collection makes it irrelevant.

    68. Re:Are templates always necessary? by mcgroarty · · Score: 1
      You are forgetting one of the biggest advantages to generics such as templates, speed. When templates are used much if not all of the binding is accomplished statically at compile time, when inheritance is used much if not all of the binding occurs at runtime.

      On the flip side, STL leads to massive code redundancy and scattered data locality. In real-world use, STL tends to be slower than generic containers dealing with void pointers and passed accessors for the sorting/hashing or a generic base type with virtual functions for the sorting, etc.

      IMHO, STL's only real advantages are its offering of standardized representation for many generic algorithms, and the way it's renewed some otherwise bad programmers' interest in the same. It's more of a memetic advance than a technological one.

    69. Re: Are templates always necessary? by Anonymous Coward · · Score: 0

      Why should smart pointers "impress" a Java coder? It is simply one technique of handling memory mangagement, and is quite valid in many situations. If I want to use garbage collection in C++(the Boehm collector for example) I have the choice to do so, the choice is not imposed on me by the language. Furthermore, Java's GC pretty much ruins the object model that you get with C++.

    70. Re:Are templates always necessary? by angel'o'sphere · · Score: 1

      But you will have a casting problem as soon s your code intrfaces with mine.

      As I hate template agnostic programmers, I put allways a wrong object into their "generic" data structures.

      And when they take it :-) BOOM.

      Hm ... with templates I had much more work to get your code make BOOM.

      The above is just kidding ... think about it and you get my point.

      angel'o'sphere

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    71. Re:Are templates always necessary? by angel'o'sphere · · Score: 1

      thats wrong!!

      Using reflection:
      if (x.getClass() == Number.class)

      is exactly the same like your:

      if (x instance of Number)

      Its even exactly the same byte code ...

      angel'o'sphere

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    72. Re:Are templates always necessary? by Politburo · · Score: 1

      The real point is: if you're safe and do some type checking, you'll never have a problem in any situation.

    73. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      No it's fine, he's not using proper terminology:

      "ensure cast" = preserve the data type

      "I lose cast." = can't guarantee the correct data type

      "have to force cast" = have to cast it to the desired type

    74. Re:Are templates always necessary? by bunratty · · Score: 1
      Thank God no idiot modded you up. You couldn't be more wrong. Try running this code:
      public class TryIt {
      public static void main(String[] args) {
      Object x = new Integer(3);
      System.out.println(x instanceof Number);
      System.out.println(x.getClass() == Number.class);
      }
      }

      Here's the output of running the code:
      true
      false

      Here's the bytecode for the first test:
      13 instanceof #10 <Class java.lang.Number>

      Here's the bytecode for the second test:
      22 aload_1
      23 invokevirtual #12 <Method java.lang.Class getClass()>
      26 getstatic #13 <Field java.lang.Class class$java$lang$Number>
      29 ifnonnull 44
      32 ldc #14 <String "java.lang.Number">
      34 invokestatic #15 <Method java.lang.Class class$(java.lang.String)>
      37 dup
      38 putstatic #13 <Field java.lang.Class class$java$lang$Number>
      41 goto 47
      44 getstatic #13 <Field java.lang.Class class$java$lang$Number>
      47 if_acmpne 54
      50 iconst_1
      51 goto 55
      54 iconst_0

      Now go compile and run that code yourself and use javap -c and look at the bytecode. Then read what I originally wrote again and come back with a more sensible response!

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    75. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      an STL map or vector working on types directly is much more space efficient than any OO container-based approach

      No. Each map or vector decleration of a new type generates all new code to implement the template with the specified type. This is known as Template Code Bloat.

    76. Re:Are templates always necessary? by bunratty · · Score: 1
      Sorry, I forgot one bytecode for the first test, which uses instanceof:
      12 aload_1
      13 instanceof #10 <Class java.lang.Number>
      Of course x has to be pushed onto the stack before we can test if it's a Number.

      The response to my challenge brilliantly demonstrated my point about reflection. It's way trickier than it looks! DON'T USE REFLECTION IF AT ALL POSSIBLE!!!

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    77. Re:Are templates always necessary? by jaoswald · · Score: 1


      For sure. Actually, your sig encapsulates the advantages nicely:

      if (!signature) throw std::runtime_error("No sig!");

      The template version would give a compile-time error instead - type-safe and no need to to runtime error handling!


      Only if the signature presence had to be determined at compile time. How flexible is that?

    78. Re:Are templates always necessary? by jaoswald · · Score: 3, Interesting

      This whole compile-time vs. run-time error business is a red herring.

      When you say getting an error at compile-time is better, you are just saying that C++ ensures that your program fits in the straitjacket that you made for it, ignoring the fact that you've made a straitjacket in the first place!

      Making a stack which is "int only" is totally specialized. How are you "accidentally" going to write code that asks for something else, if your problem is so focussed that it only needs ints?
      You really think that using strings by mistake is going to be a major source of bugs?

      The real problem is that C++ operations are type-specialized at compile time. C++ compilers, for instance, don't know how to add numbers unless they know the type at compile time. In a dynamic language, the addition operator knows how to add whatever numbers it sees at run-time.

      For every set of bugs that a compile-time error catches, there is a corresponding set of desirable program behaviors that become more difficult to explain to the compiler. That's why the whole idea of "design patterns" caught fire in the C++ world. These design patterns are like a phrase book translating your desire into the C++ language. If you have a more flexible language, you don't need a phrase book as often!

    79. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      That's why Java has the "instanceof" operator. You can do:

      Stack javaStack = new Stack();
      javaStack.push( new Integer( 12 ));
      Object blah = javaStack.pop();
      if( blah instanceof Integer ) { /* do some wicked cool integer related stuff! */
      } else { /* ignore, or whatever */
      }

    80. Re:Are templates always necessary? by Old+Wolf · · Score: 2

      If you're writing production code then you don't want weird exceptions throwing up all over the place. I'd far rather make the straitjacket I want and then keep to it, than have a higher risk of my program barfing.

      For example, with the Stack cast to int before - what if the stack definition is somewhere over the other part of the program, and one member of the team decides it should be a stack of vectors (or something), and your code to pop an int is in a very rare situation (so it may get missed in blackbox testing) ?

    81. Re:Are templates always necessary? by Old+Wolf · · Score: 1

      Well said. Let's not also forget that the template parameters don't have to be data types, for example they can be the bounds of some sort of collection - or even a flag for some function/class that looks much more elegant that #if .. #elif ... everywhere

    82. Re:Are templates always necessary? by bunratty · · Score: 1
      Here's the answer:
      if (Number.class.isAssignableFrom(x.getClass()))

      I switched the Number.class and x.getClass() when I first wrote it, and actually wrote Integer.class instead of Number.class at first. Reflection code is not easy to get right!

      Additionally, the instanceof test took about 40 nanoseconds and the reflection test took about 600 nanoseconds on my computer. Reflection code is about an order of magnitude slower, and about an order of magnitude harder to write.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    83. Re:Are templates always necessary? by truth_revealed · · Score: 1

      I was referring to the data stored within the STL vector or map being very space efficient. As for template code bloat - it's getting less so with modern C++ compilers. Furthermore, only the template functions actually used by the program are actually linked into the executable. Because STL does not use virtual functions programs using these templates can be highly optimized. Some compilers even share template methods between types if the type does not affect the generated code. However, I will concede that all this intense optimization does take a lot of compile time and memory. Some scarier template-heavy source files I've encountered using Boost have used 500 megs of RAM to compile under high optimization; but the final .o file size was very respectable.

    84. Re:Are templates always necessary? by OneEyedApe · · Score: 1

      If the signature presence had to be determined at compile time, this would be advantagous. But it does not neccessarily have to be so.

      --
      Life sucks, but death doesn't put out at all....
      --Thomas J. Kopp
    85. Re:Are templates always necessary? by Anonymous Coward · · Score: 0

      Some people just hate java. Its either the object model, the speed (which isn't an issue anymore), or the 'memory bloat'. Ignore those comments, its just angry coders that aren't up to speed with java (or coded in it once when it was java1.1).

      Or, people like me, who have coded in Java quite recently (1st year Uni has 2 Java courses), who know C++ thoroughly, but can't _quite_ do as well in Java. For many reasons. Mostly, I feel restricted by the GC, the lack of templates, the insistance on always using a pointer, except for primitives, which you can't have a pointer for, and numerous other things like that, which are just niggly. Now, I'm not one to say that Java's completely braindead... they've got some good ideas. I mostly hate the implementation and API.

      Lazarius

    86. Re:Are templates always necessary? by jaoswald · · Score: 2, Insightful

      Look, if you are dealing with a team that has not divided responsibility for design decisions according to a clear system, then that is your real problem, not the lack of compile-time diagnostics. You're also going to get huge numbers of bugs that the compiler *won't* catch.

      The problem with C++ in particular is that it is a bondage-and-discipline language. Everyone on your team has to figure out in advance what chains and barriers are going to be put up in order to allow the problem to be solved within the C++ language.

      In a dynamic language, you *choose* what barriers to put in place in order to maintain safety. You aren't forced to put a lot of barriers up that will never be needed.

      Also, what people miss is that in Lisp, for instance, a run-time error usually puts you in an interactive debug environment, allowing you to make changes to the program (still alive) using the full power of the Lisp language, and the full resources of your program, in order to find the problem, fix it, and continue execution. This is just now coming to pass in the C++ world, with incremental compilation, etc., but Lisp programmers have had this for decades. When you are developing, you will find the errors, and for production, you can write error handlers that catch these various conditions, log them as appropriate, and specify how execution should continue.

      The strategies you use with a dynamic language to prevent and deal with these kinds of problems are different than with static languages like C++. The strategies aren't better or worse, just different. What you gain with dynamic languages is a kind of flexibility that allows you to attack the problem, not the language, and to do so with a maximum payoff for programmer effort. What you gain with C++ is the ability to catch certain types of errors, which aren't really that common, especially as intellisense-type tools are becoming much more widespread. Much of the time, when the compiler complains about type mismatches, you add a cast. The language is forcing you to explain yourself again, not really pointing out a logic error in your program.

      The real problems that programmers face are errors of logic, which no language can address, and the ability to express the desired operation, which dynamic languages make much easier than static languages, because they don't require as much unnecessary or redundant description.

    87. Re:Are templates always necessary? by Old+Wolf · · Score: 1

      Well you're basically arguing that functional languages are better than C++ . Which is rubbish, each has its own place.

      BTW how often do I use casts in C++? (ignoring dynamic_cast which is an integral part of polymorphism) umm, once a month? If you design well, as you keep going on about, you won't need weird casts all over the place.

    88. Re:Are templates always necessary? by angel'o'sphere · · Score: 1

      LOL, you are right.

      However I'm totaly surprised about the bytecode you show.

      It should be:
      invokevirtual #12 <Method java.lang.Class getClass()>
      getstatic #13 <Field java.lang.Class class$java$lang$Number>
      if_acmpne label

      And nothing more.

      ALSO: you omit some part of the first test, loading x onto the stack and the test/branch as well.

      Both test need exact 3 opcodes.

      BTW: instanceof and my approach are not the same semantics ... instanceof would allow subclasses, as you showed, and has an according overhead in the VM, while my approach is exact and faster.

      Obviously the compiler you used generates over complicated code, sorry, have mine not here but I asume it generates the same code.

      So I was wrong regarding "exact same byte code".

      And you are still wrong regarding speed :-)

      angel'o'sphere

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  2. Bloat by warmcat · · Score: 2, Insightful

    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 used templates have anything to say about templates and bloat?

    1. Re:Bloat by Buck2 · · Score: 5, Insightful

      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.

      --

      As my father lik@(munch munch)... ....
    2. Re:Bloat by Malc · · Score: 4, Insightful

      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*.

    3. Re:Bloat by Anonymous Coward · · Score: 1, Insightful

      Templates are an organizational tool, not an optimization tool. They give the developer parametric polymorphism at design time, so she can deal with one "customizable" class instead of 20 slight modifications. The code size is correspondingly shrunk.

      This organizational tool comes at a price: the compiler expands each type as it would a #define function, so while your code size is nice and small, easy to read, your image size can really bloat. Also, I haven't seen a symbolic debugger work perfectly with templates.

      In my experience, templates are a great refactoring tool when you can afford a larger footprint. Otherwise, they are cumbersome and unnecessary. I guess it really depends on your particular application and target platform... developer experience should be taken into account as well.

    4. Re:Bloat by Malc · · Score: 4, Interesting

      "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.

    5. Re:Bloat by Anonymous Coward · · Score: 1
      My understanding is that the template mechanism is like a super #define

      This is correct. However if you're a die-hard OO guy then you've probably found yourself writing wrappers for the atomic types (CInteger, CFloat etc) for some purposes - yuk! Templates are meant to avoid this kind of thing, and the fact that you get multiple versions of each functions means that:
      • you don't get a speed hit from virtual function calls
      • Each version is optimised for it's own particular type
      So you're right, it might bloat the binary (slightly) but it will make your source more beautiful and your code run faster. (If you use them in the right circumstances, duh)
    6. Re:Bloat by Anonymous Coward · · Score: 0

      Templates do not cause code bloat!

      In cases where a common implementation is desirable you can always wrap a non template implementation with a 100% inline template wrapper. The wrapper will add the type safety benifits of templates without bloat.

      In many other cases code can be eliminated from an executable using templates. Virtual functions are often included in executable files even if they can never be called. A well designed template implementation will allow the compiler to eliminate functions that are never called.

    7. Re:Bloat by Buck2 · · Score: 1

      Well, thankfully, with a library like blitz++, which is mostly just a means of providing matrix-like containers, it's normally pretty easy to figure out what you are doing wrong regardless of the pages of template-related errors that g++ might spit out. As long as you have faith that the monster-mash of templates that you are using is clean, you can sort out your own code with the only compile-error line starting with "instantiated from here" that actually has a reference to some code you've written yourself. :)

      A humorous, if you're sick, thing to do is to index into a blitz::Array with a float or double ... this generates about 20 pages of completely impenetrable errors. Just classic. It can easily blow the minds of beginners and completely pisses people off that are switching from Java in a Windows environment to, say, a g++/Linux mode. Heh.

      --

      As my father lik@(munch munch)... ....
    8. Re:Bloat by SquareOfS · · Score: 1
      I was actually going to bring up Blitz++ as well . . . as an example of when templates are both remarkably useful and mind-bendingly obscure.

      I'm not a language designer, but it seems to me that what is needed is some kind of a compromise or hybrid between the intended Java approach to templates/generics and the C++ approach.

      If memory serves, Java templates are going to be implemented by erasure, a la GJ. The point behind this is that Java needs bytecode backwards compatibility, so it can't adopt parametric types into the runtime language.

      Basically, the compiler will use generics to figure out whether or not operations are guaranteed type-safe and then do the casting for you. (Not sure if it's bright enough to pull off making the cast cheap once it's known to be safe; also not sure if this is safe during reflection. Check out this comment and the discussion surrounding it for more.)

      Anyway, if erasure can be made cheap (i.e., without the cost of <dynamic_cast>) then doing (at least basic) templates with erasure could resovle some of the issues with #define templatizing. So you could leave the truly hairy stuff with C++ style templates and simple collection manipulation with erasure-templates.

      Now I'll wait for someone to tell me why this is a horrible idea.

    9. Re:Bloat by Malc · · Score: 1

      Heh: I guess the messages are more confusing to C++ newbies in most situations. The only time I've had problems with them recently was after compiler upgrades... which makes it rather harder to track (VC++ doesn't tell you "instanciated from here".) Commenting out huge portions of code is the quickest way to locate the problematic line in this situation ;)

    10. Re:Bloat by Henry+V+.009 · · Score: 2, Interesting

      They give the developer parametric polymorphism at design time, so she can deal with one "customizable" class instead of 20 slight modifications.

      I gotta ask, when you think of a programmer, do you actually think of a girl programming? I mean good god, that 'she' thing as the neutral pronoun is more than a little phony isn't it? More women are graduating from colleges than men. They simply aren't choosing programming as a career in large numbers. Sorry, but it's a male-orientated profession. And I happen to know that you, as a human being, when you think of some generic programmer, think of a male. Probably a fat, coca-cola guzzling male.

      Despite that mental image, your instinct for double-think kicks in. You choose the female pronoun for a host of social reasons.

      And sorry, I don't like double-think, so I'm attacking you for it. Nobody talks like that in normal conversation. It's a middle-school English teacher grammar meme. A virus.

    11. Re:Bloat by jkujawa · · Score: 2, Interesting

      You cannot use C++ effectively and safely without templates.

      The STL, especially, makes C++ an order of magnitude more usable and powerful.

    12. Re:Bloat by Gortbusters.org · · Score: 3, Insightful

      True that. Not using the STL is like saying you will rewrite the entire Java API for your application, save the base Object.

      Some people say they use the good ole void* instead of a template. Those people sometimes do memory debugging for months.

      --
      --------
      Free your mind.
    13. Re:Bloat by (startx) · · Score: 1

      STL is a godsend. that is all.

    14. Re:Bloat by Waffle+Iron · · Score: 3, Redundant
      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.

    15. Re:Bloat by vidarh · · Score: 4, Informative
      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.

    16. Re:Bloat by Buck2 · · Score: 1

      Well, what can happen with matrix libraries in C++, is that many people design them using inheritance and whatnot. Templates, I was under the impression, if used "all the way to the bottom" can be a faster way to go about it.

      Blitz++ compares fairly well to Fortran. That's pretty good for me.

      --

      As my father lik@(munch munch)... ....
    17. Re:Bloat by magic · · Score: 1
      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?


      -m

    18. Re:Bloat by Hayzeus · · Score: 1
      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 useful tools, can hide enough underlying complexity that a naive programmer can underestimate the actual amount of code generated for a given template instantiated over many types. This is a programmer issue, though, not a template issue.

    19. Re:Bloat by emin · · Score: 1

      Templates are particulary useful and efficient for container classes like hash tables.

    20. Re:Bloat by bunratty · · Score: 1
      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.
      --
      What a fool believes, he sees, no wise man has the power to reason away.
    21. Re:Bloat by Anonymous Coward · · Score: 0

      You have to consider the most basic alternative to writing templates, namely writing lots of versions of the same thing just to handle different types. So templates can drastically reduce source-code bloat. They don't even increase object-code bloat (a far less important issue, imho) because the compiler only generates the versions you actually use.

    22. Re:Bloat by Viol8 · · Score: 1

      You have to remember that some guys are such wusses that much less talk to a girl they're actually
      *scared* of them and they use this kind of politically correct double-speak because they're afraid
      some rampant feminist will track them down and whip them till they bark if they mention anything male oriented in speech or writing.

    23. Re:Bloat by Tim+Browse · · Score: 1
      You cannot use C++ effectively and safely without templates.

      I think this is the kind of thing that usually bugs me about discussions on STL/generic programming/templates. Advocates will insist on saying silly things like this.

      I mean, do you honestly believe that not a single one of the many C++ projects that exist in the world that do not use templates have not been effective?

      It's like when I read an interview with Stepanov, where he claimed that object-oriented design was "useless".

      I mean, there's a difference between honest assessment of what you do and don't like, and what you have found is most effective, but to claim things like you're not using C++ effectively unless you use templates, or that object-oriented design is useless (tablizer need not apply) is just unhelpful and somewhat arrogant.

    24. Re:Bloat by Ed+Avis · · Score: 1

      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 languages.

      Also, in the STL there is a single implementation of most containers specialized for pointers, so a vector and a vector share a single lump of object code. (As you'd expect, since all pointers are the same size no matter what the type of thing they point to.)

      I think that on the whole the speed advantages of generating code specialized to a single type, with fewer branches and comparisons at run time, outweighs the cache thrashing effects of generating larger object code. If you disagree, you are free to only use containers of pointers and thus share a single implementation for all your containers, as would probably happen if you used an equivalent container library in C.

      But at the end of the day, if you are worried about speed, benchmark. Otherwise, concentrate on writing code which is correct and whose meaning is clear to a human reader. Templates certainly help with both of those, at least for the experienced C++ programmer.

      --
      -- Ed Avis ed@membled.com
    25. Re:Bloat by Viol8 · · Score: 1

      Yeah , I can just see lots of C++ unix programmers disassembling their porgram to try and read the
      Sparc or PA-RISC or PowerPC assembly code to check the optimisation levels. Not!
      You ever tried to code in RISC assembler?? It aint quit the walk in the park that x86 assembler is by comparison!
      Get real.

    26. Re:Bloat by warmcat · · Score: 2, Insightful
      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 templated across 24 types - are very important.

      Sure for some types of work the longevity and conciseness of the code is more important than the efficiency, I understand that. And in those types of work you can basically forget that you are running on real hardware with real limitations, since time and memory will 'stretch' for you. But just like it sounds you wouldn't hire me, I don't think for my kind of work I would hire you :-)

    27. Re:Bloat by Jeremi · · Score: 1
      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 extremely bug prone.


      With templates, you just declare a container type corresponding to the type you want it to hold, and you're done -- no need to write redundant code, and all your operations on that container are properly type-checked by the compiler. This means you can write a lot more correct code in a lot less time. Yes, it causes some bloat, but often it's well worth it.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    28. Re:Bloat by Ed+Avis · · Score: 1

      I meant to say, a vector and a vector share the same code. But Slashdot did its usual stupid HTMLization on my comment.

      --
      -- Ed Avis ed@membled.com
    29. Re:Bloat by Anonymous Coward · · Score: 0

      I don't think you understand how templates work.

      What do you mean by "templated across 24 types"? You mean you're using a template with 24 different types? Sure, if you instantiate a template with 24 different types you might get 24 copies of functions that are template specific. But if you really are using 24 different types, you would need those functions anyway.

      If you're talking about saving the overhead by making a class very generic (without templates) then that's a different ballgame. Templates may not be appropriate for that use. But this doesn't mean templates are good for nothing.

    30. Re:Bloat by Cereal+Box · · Score: 1

      I'd mod you up if I had mod points at the moment. I've always hated this desire to tend towards "she" as a neutral pronoun in cases where it obviously does not apply in the general case. I guess the thinking is that if enough people see this usage we'll start to think of women as being programmers or something.

    31. Re:Bloat by Cereal+Box · · Score: 1

      ... And by that last comment I meant that we'll start to think of programmers as mostly being women instead of men. Not likely, since reality says otherwise.

    32. Re:Bloat by dabootsie · · Score: 1

      Template class methods that you don't use are not carried over into object code. You can also handle multiple data types using the same code which allows you to have a very large and robust class, promoting code reuse without penalties to efficiency. This is the major advantage to templates over large general-purpose classes.

      For example:

      template <class T>
      class MyClass {
      private:
      T val;

      public:
      MyClass(){ val = (T)0; } /* null/zero whatever type T is */
      MyClass(const T& in){ val = in; }

      /* do something different depending on what we're given */
      void polymorphic_op_one(int);
      void polymorphic_op_one(float);
      void polymorphic_op_one(void*);
      void polymorphic_op_two(int);
      void polymorphic_op_two(float);
      void polymorphic_op_two(void*);
      /* accessor/mutator */
      T getval(void);
      void setval(T);
      /* overloaded stream operators */
      friend ostream& operator<<(ostream&, T*);
      friend istream& operator>>(istream&, T*);
      };

      Nothing too fancy. One instance variable, simple constructors, two different ops for each of int, float, or void pointer. Has an accessor and a mutator, and overloaded stream operators.

      Let's say you were to create a MyClass object with T as type int, using the default constructor, then your program called only the polymorphic_op_one method and the output stream overloaded operator.

      Only MyClass(), polymorphic_op_one(int), and << would be built into object code. If this weren't a template, it would ALL be built into object code and clutter up your program. Like Java, which would be bad. ;)

    33. Re:Bloat by makapuf · · Score: 1

      Alexander Alexandrescu : maybe you meant Alexei ..

    34. Re:Bloat by vidarh · · Score: 4, Interesting
      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.

    35. Re:Bloat by vidarh · · Score: 2, Informative

      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.

    36. Re:Bloat by vidarh · · Score: 1

      Of course... Arghh, the curse of Friday afternoons :-)

    37. Re:Bloat by babyblink · · Score: 1

      8 years ago I know C++, wrote ~20k line of code in it.. Now I don't even know how to read the code.. I'm thinking of relearning COBOL anyway.

      --
      [self dealloc];
    38. Re:Bloat by vidarh · · Score: 1
      You don't need to. You need to understand what the compiler optimizes away and what it doesn't. My capability for reading x86 assembly is mediocre at best, but I certainly read it well enough to see when I've done something that makes GCC suddenly collapse a few hundred lines of code down to a compile time constant value by structuring my template code in a way that is "optimizer friendly".

      The typical reason for doing so in C++ is to be able to highly specialize a template to a particular usage. Say you need a sort that needs to be efficient on a very specific set of data. Quicksort is a good overall choice, but you can do vastly better if you can provide hints about your input. With templates you can still write a generic sort that will compose the right algorithm for you by inlining code and having the optimizer collapse it all down to a single function for you depending on information you provide (a typical example would be to sort subsets of the data of a certain size or below with a more specialized sorting algorithm)

      In that case, even someone who has never seen assembly before will notice the difference easily just be looking at executable size and do some basic benchmarking - the advantage of looking at the assembly is that even with just a basic knowledge of assembly you will get a much better overview of why the damn compiler didn't optimize away as much as you'd hoped.

    39. Re:Bloat by cheezfreek · · Score: 1
      Sure, if you're compiling with no optimization, templates sure can create bloat. Another poster has pointed out that if you write intelligently, template stuff can be faster than code using inheritance and polymorphism.

      What I haven't seen pointed out yet is that a smart interprocedural optimizer can factor out a lot of the bloat. Some functions will be identical regardless of template parameters. The duplicates can be eliminated and the code that calls these functions can be changed to just call the remaining function.

      Other functions will be the same in large portions of the code (when you get down to an intermediate language level). These portions can be outlined (the opposite of inlining) and then the resulting duplicate functions can be eliminated, taking out more bloat.

      And please, no one say that this can't realistically be done, because I know of one implementation that can actually do this.

    40. Re:Bloat by vidarh · · Score: 1
      If you define "use effectively" as "exploit the features of the language to it's full potential", then there's no way around templates in C++ - it is one of the primary benefits above C for instance. If I had to choose between classes+inheritance and templates and not use the other, I'd choose templates hands down - classes are easy to emulate just by being structured (been there, done that, implemented several OO class hierarchies using plain C)

      I don't think object oriented design is useless - the combination of templates and OO is even more powerful than each of them on their own, but if you use C++ and don't use templates you're ignoring a major part of the language, and perhaps the largest single part of the language that differentiates it from many alternatives and that is difficult to emulate with other language features in any meaningful way.

      If you define "use effectively" as "accomplishing a specific goal", then of course you can do that in C++ without templates, but not exploiting the advantages of templates make the case for using C++ over language Foo or Bar much less compelling.

    41. Re:Bloat by Ed+Avis · · Score: 1

      Ah. In that case, an STL implementation that uses a single vector specialization wouldn't be portable. But still, surely most C++ systems in practice have all pointers the same size, otherwise this technique would not be mentioned so often (I think it even appears in Stroustrup's book).

      I always thought that on a platform that couldn't address every single byte, you'd simply make sure that chars were word-aligned. After all, i386 hardware cannot address individual bits, but who heard of a C++ implementation where a bool * was larger than other pointer types?

      --
      -- Ed Avis ed@membled.com
    42. Re:Bloat by SpeedBump0619 · · Score: 1

      Does anyone who has used templates have anything to say about templates and bloat?

      Absolutely. Templates only create code "bloat" in one of two situations. The first is high coupling between algorythm and it's underlying type and second is poor implementation.

      The basics: Use templates to perform the type specific portions of an algorythm, and use a common base class for the template which does all of the generic work. The less generic work in the algo the more code "bloat" will happen. But again, if the algo isn't generic then you would have needed multiple implementations just using c...you loose nothing by using templates, and you gain automatic extension to new types.

      class MyBase {
      protected:
      void genericPart();
      };

      template
      class MyTemplate : public MyBase {
      public:
      inline void typeSpecificPart() {
      //do type specific stuff
      genericPart();
      }
      };

      void MyBase::genericPart() {
      //perform generic algo components
      //when type specific data/behavior needed call
      typeSpecificPart();
      }

      this works beautifully for most kinds of generic containers, since it places all of the type checking within the type aware template, but puts all of the generic container logic in a common set of routines. Properly implemented this can make a typesafe stack, queue, list, set, etc, routine which is *exactly* the same size and performance as a completely non type-safe container.

      Understanding and properly using templates allows you to program at a higher level of abstraction. It will make you more marketable, more capable of effectively solving problems, and more likely to generate reusable solutions. Don't just dismiss them...if you think they aren't useful then you probably don't understand their use.

      -SpeedBump

    43. Re:Bloat by IWannaBeAnAC · · Score: 2, Informative
      Where did you get that idea? You are completely wrong.

      There is no difference at all in performance cost of a template function versus a non-template function. The generated code is exactly the same as if you had explicitly written a non-template function to do the same thing. So there is no performance loss at all due to template. (There might be due to some poor usage of templates, but you could say that about anything, even assembly language!)

      On the other hand, templates allow a style of code that retains some flavour of OO polymorphism while being very fast, as all of the function calls etc are resolved at compile-time. The alternatives are to use dynamic polymorphism (slow), or bloat the source code by manually writing stupid functions like

      void foo_SomeType(SomeType x) { ... }
      void foo_SomeOtherType(SomeOtherType x) { ... }
      ...

    44. Re:Bloat by IWannaBeAnAC · · Score: 1
      And compilers are getting much better at doing this optimization themselves, even in cases where it would be hard to do manually (say, for templates instantiated on both int and long, on a platform where these have the same representation).

      The parent was probably put off by some bad experience with an older compiler.

    45. Re:Bloat by IWannaBeAnAC · · Score: 1
      Hey, I looked at your hash_map implementation a while ago. I thought it was nice, but I didn't end up using it for a few reasons (none terribly major):

      Inconsistent capitalization of method names. I guess you put the 'semi-standard' names in lower case for consistency with the STL containers, but then having other methods in UpperCaseStyle looks weird.

      Why use my_pair instead of std::pair?

      I couldn't convince myself that your hashing itself was correct, especially when deleting items. Rather than 'chaining' items when a hash collision occurs (using a list of some sort), you probe for an empty bucket with (hashLocation + hashIncrement)%maxLength. This means that the delete function must probe ahead and see if other objects need to be moved into its place. But I don't see how that works from looking at the code.

      I ended up writing my own, based (loosly) on Matt Austern's standard library proposal, using the doublely linked list scheme. It turned out to be very elegant, the iterator type is just list::iterator, so no need to write a custom iterator class. The only thing I didn't get right is the complexity requirements for the bucket interface, but I don't use that anyway so I havn't bothered trying to fix it.

    46. Re:Bloat by Anonymous Coward · · Score: 0

      > In my reactionary way I continue to believe my
      > prejudices.

      Awesome! In my reactionary way I say code size might be bigger, but it will be way faster!

    47. Re:Bloat by IWannaBeAnAC · · Score: 2, 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 casts all provide the programmer with more tools, and have no intrinsic performance issues while allowing more flexibility of program design.

      In other words, the reason why embedded C++ is so disparaged in the mainstream C++ community is that the subset of C++ it implements is based more around what is easy for compiler writers to implement, rather than what is desirable for a programmer in an embedded environment.

      In some forms of template programming, with some compilers, there is a bloat problem. For the most part, this has been fixed by better compilers (recognising when two different instantiations produce equivalent code) and better design.

    48. Re:Bloat by ucblockhead · · Score: 1

      And in fact, anyone who wrote C++ programs under DOS and/or Win 3.1 used a compiler that had pointers of differing sizes. (Though using nonstandard keywords like "near" and "far".)

      --
      The cake is a pie
    49. Re:Bloat by scotch · · Score: 1

      sizeof (bool) typically is 1 byte, possible larger, i've never heard of it being smaller

      --
      XML causes global warming.
    50. Re:Bloat by IWannaBeAnAC · · Score: 1
      Actually, it does require that all pointers to class types must be the same size. Pointers to builtin types and pointers to functions and pointers to members can be different sizes.

      It is also guaranteed that a cast to void* and back preserves all information.

      In fact, POSIX requires that in C, all pointers are the same size (or at least convertible to one another without losing information). That doesn't apply to pointers to members, of course.

    51. Re:Bloat by ucblockhead · · Score: 2, Informative
      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 three megabytes of memory when run.

      --
      The cake is a pie
    52. Re:Bloat by AT · · Score: 1

      Yeah, I wish they'd just get rid of the whole allocator concept entirely. I've used templates fairly extensively, and have *never* seen any use of allocators other than the default. My understanding is that the whole allocator scheme was invented to overcome limitations back when we had 16-bit compilers and "far" pointers. All they seem to do is clutter up type names and obfuscate error messages.

      Are there any useful applications of allocators, that can't be done better by overloading new?

    53. Re:Bloat by Anonymous Coward · · Score: 0

      [self new]; while(TRUE) [self retain];

    54. Re:Bloat by uid8472 · · Score: 1

      I've used templates fairly extensively, and have *never* seen any use of allocators other than the default.

      They can come in handy when you're trying to use STL (er, C++ Standard Library) containers with, say, garbage collection.

    55. Re:Bloat by angel'o'sphere · · Score: 1


      Does anyone who has used templates have anything to say about templates and bloat?


      Hm ... why don't you read a book about it?

      a) there are linkers removing the bloat
      b) you can design yoour templates to avoid it (by using void * generic base classes and putting templatified wrappers for type safty in front of it)

      Anyway, you need to work with templates for some years, just like with any other language feature, to get a master in it.

      So its definitly time to start reading a book now.

      If you not even use STL .... then you are an .... anyway. ((Insert some bad word wich would get me modded as flaim bait :-) e.g. idiot))

      STL has no performance and no bload overhead. and every STL book explains WHY.

      angel'o'sphere

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    56. Re:Bloat by Old+Wolf · · Score: 1

      Yes you're right, although you should have spelled it out more that you meant code size bloat, not slowness, as there seem to be a whole bunch of people saying their template code runs fast :)

      These days, runtime speed and reducing development time are more important than file size, it seems.

    57. Re:Bloat by Old+Wolf · · Score: 1

      I do lots of C++ programming but never use the STL. The reason for this is that I have never seen a tutorial for it that doesn't completely suck. Can you recommend any?

    58. Re:Bloat by vidarh · · Score: 1
      Ah, no. Void pointers are explicitly required to be able to hold a pointer to any type. 3.9.2.4 in the ISO C++ standard has the following to say on the subject: "Objects of cv-qualified (3.9.3) or cv-unqualified type void * (pointer to void), can be used to point to objects of unknown type. A void * shall be able to hold any object pointer. A cv-qualified or cv-unqualified (3.9.3) void * shall have the same representation and alignment requirements as a cv-qualified or cv-unqualified char*." [cv-qualified/cv-unqualified refer to const and volatile qualifiers]

      In other words casting to void * is always allowed, but casting "Foo *" to "Bar *" where Foo and Bar are unrelated types might cause you to lose information.

    59. Re:Bloat by complexmath · · Score: 1

      An instance of a template is created for every type that template is applied to, but only when explicitly necessary. So say I create a list and a list, you will end up with the class declarations for both compiled into your application. But say that from these two lists you only ever call list::foo(). This function call is the only code that the compiler ever instantiates in your application. So from your two lists you end up with two class declarations and the code for one function call. Some code bloat.

      And as others have said there are other substantial advantages to using templates. Complex code generation, type safety, algorithm genericity, etc.

      Personally, I would not hire someone as a C++ programmer who did not demonstrate at least a reasonable understanding of templates. If you're ignoring this facet of C++ out of some unfounded fear of code bloat I gurantee you're doing yourself a grave disservice.

    60. Re:Bloat by vidarh · · Score: 1
      I was under the impression that even pointers to unrelated classes could have different size. Can you point me to where in the standard it says specify that all pointers to class types must be the same type? I'm genuinely curious. 3.9.2.3 says "The value representation of pointer types is implementation-defined. Pointers to cv-qualified and cv-unqualified versions (3.9.3) of layout-compatible types shall have the same value representation and alignment requirements (3.9)".

      I can't find any language that narrow it down further, except for stating that all types must be convertible to/from void *, and that char * and void * must have the same value representation and alignment requirements (3.9.2.4)

      The standards document is big, though, so I wouldn't be surprised if I've missed some paragraph that narrows it further down, so if you have a reference it would be appreciated.

    61. Re:Bloat by Arandir · · Score: 1

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

      Don't mistake that extra ten pounds as fat when it could in fact be muscle.

      Let's take a concrete example. Let's say you want have doubly linked list of Fubar objects and another for Snafu objects. Furthermore, these classes are not in the same inheritance hierarchy. Implementing this with the STL takes extremely little work, but you end up instantiating implementations for two completely different doubly linked lists. Is this bloat?

      Now let's look at non-STL C++. One way to do this is to create two different doubly linked lists with member data and functions in the Fubar and Snafu classes. For considerably more work, you end up with the same level of "bloat". So let's go to method number two, and use our handy-dandy generic list that holds void pointers to whatever we want. It's only half the size of the STL implementation, but you've completely lost all type safety. To make up for that, you use RTTI, which is hardly bloat-free and introduces other problems.

      With the STL, you debug symbols are going to be significantly larger. But strip your statically linked binaries and you'll find that STL and non-STL executables that do exactly the same work are going to be nearly the same size.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    62. Re:Bloat by Banjonardo · · Score: 1

      Helpful for learning, though. In my High School C++ class, we use special templated classes made by the College Board called apvectors and apmatrices (these are arrays protected against accessing non-existant elements..). We also use apstacks, apstrings, and apqueues. They are very helpful in learning important ways to store data and other concepts. They're also very useful to help us understand classes when we get to that chapter, cause then we can read their code and understand how they work.

      --

      -----

      Score 3? For what? Being wrong, at length? - smirkleton

    63. Re:Bloat by be-fan · · Score: 1

      ::digs book out from under chair::
      Perhaps *you* meant Andrei?

      --
      A deep unwavering belief is a sure sign you're missing something...
    64. Re:Bloat by be-fan · · Score: 1

      I think the "she" usage if fine. Males have been favored in our culture for decades and still are. One extra letter, giving women a little nod indicating that things are changing is the least we can do.

      --
      A deep unwavering belief is a sure sign you're missing something...
    65. Re:Bloat by Garen · · Score: 1

      Templates offer compilers enourmous opportunities for optimization, inparticular constant folding and dead-code-elimination.

      The whole "templates cause bloat" is something of an implementation problem that can probably be blamed especially on MSVC6.

    66. Re:Bloat by be-fan · · Score: 1

      I've been thinking of this for awhile. We need a abstract representation of class templates. This would not only make it easier to factor out identical instances, but it would allow for runtime code generation, meaning that you could distribute "real" template libraries where users could instantiate templates with their own types.

      --
      A deep unwavering belief is a sure sign you're missing something...
    67. Re:Bloat by jdennett · · Score: 1

      The C++ template system is a Turing-complete programming system. Yup, you can compute things using the type system at compile-time. This allows for remarkable optimizations in compiled code.

      Bloat can be avoided in a number of ways, and in any case is never worse than if you wrote equivalent code without using templates.

      Templates are not a super #define.

      Used without understanding, templates can produce bad code. As can any other language features. Used wisely, templates can give elegant, efficient code that is is hard/virtually impossible to achieve in other ways.

    68. Re:Bloat by IWannaBeAnAC · · Score: 1

      Not same type, but same sizeof() & representation. I don't have a copy of the standard handy, and I can't find any other references; perhaps I was mistaken?

    69. Re:Bloat by Anonymous Coward · · Score: 0

      In truly low-level code, memory allocations aren't something you want happening "behind your back", like it does when using STL lists, maps etc.

      You also get much better performance and caching when things like list linkage are part of your core data structures.

      I have implemented templates that support this, but they require some hairy macros to work.

    70. Re:Bloat by Malcolm+Chan · · Score: 1

      I have to say, an embedded system with 4MB flash and 4MB RAM does not sound small.

      In my line of embedded systems work, the usual micro would have 64KB address space, partitioned into RAM and ROM. In such situations, I personally also abstain from C++ due to its extra memory/type overheads. Sure, you may count on having an excellent compiler to optimise out the extra code introduced from an inheritance structure, but most of the embedded (vendor specific) C++ compilers I've seen haven't been that good about it!

      I still find C best for such tight memory situations.

      --

      /MC

    71. Re:Bloat by renoX · · Score: 1

      > You ever tried to code in RISC assembler?? It aint quit the walk in the park that x86 assembler is by comparison!

      Uh? It's a matter of taste: I prefer reading RISC assembler any time than reading 86 assembler.

      As for reading the assembly output, I do it from time to time to see what the compiler has generated because I'm curious, but it is not the good way to optimise, first you should check where the time is spent before optimising.

    72. Re:Bloat by vidarh · · Score: 1

      It doesn't happen "behind your back", the behaviour is quite well behaved, and by passing an allocator you can control it even further. If you allocate many enough objects that memory allocations show up in your profiling, then implement a specialized allocator. Often, allocator classes such as small object allocator can be effectively generalized using templates so that they can be easily reused. As for list linkage, it is part of your core data structures if you make an STL list of objects instead of a list of pointers.

    73. Re:Bloat by vidarh · · Score: 1
      Ever tried installing Linux in 4MB flash and 4MB RAM and then have space left for a full set of userspace applications (shell, linker, module management, various programs such as mv,cp,ln etc)? You're not left with much for the actual application.

      Anway, what overhead from an inheritance structure? Unless you use virtual functions, there is no overhead from it if you use compiler that isn't a pile of shit. If you do use virtual functions, then yes. However, if you use virtual functions properly the size overhead of using them is often less that the size overhead of designing your system to do without. In other words, use C++ features that cost when the advantage they provide outweigh the space or performance overhead - analysing when what features are appropriate (and knowing which features introduce what cost) is an integral part of every developers job.

      I agree that using C might be the better choice in systems as small as you suggest, but the discussion was over using templates or not in C++, not about using another language. If you do make the decision to use C++, it would not make sense to not use features that can help you keep performance to a max and space to a minimum, and when properly used templates is just such a feature.

    74. Re:Bloat by Malcolm+Chan · · Score: 1
      Anway, what overhead from an inheritance structure? Unless you use virtual functions, there is no overhead from it if you use compiler that isn't a pile of shit.


      I was trying to point out that with the compilers that are commonly used/available in the small embedded world, the optimisations are not really good enough!

      As for overhead from inheritance -- using the common base class + template approach does generate more method calls, calls which are often not inlined by crappy compilers/linkers, especially if the template is in a header file used in a different module to the module defining the common base class. Additional overhead can also come from having more method calls in general, a style which is encouraged by the OO model.

      As before, this is all no problem with a good compiler/linker! But sadly, this is all too often lacking in the small embedded controller market.
      --

      /MC

    75. Re:Bloat by vidarh · · Score: 1
      The common base class + template approach does not generate more method calls by itself. You (that is, the developer) generate more more method calls if you split up methods to separate out more generic functionality than you would if size what not one of your concerns. In other words, it's a classic size vs. performance tradeoff that is a pure technical design issue.

      I have no problem agreeing with you that there's a lot of crappy compilers out there, though... :)

    76. Re:Bloat by makapuf · · Score: 1

      ahem ... (goes under the chair ..)

  3. Professional Computing Series by Anonymous Coward · · Score: 2, Informative

    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.

  4. What about Java/C++ developers by Gortbusters.org · · Score: 2, Interesting

    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.

    --
    --------
    Free your mind.
    1. Re:What about Java/C++ developers by xurble · · Score: 1

      But surely java is getting templates?

    2. Re:What about Java/C++ developers by Gortbusters.org · · Score: 1

      Now I know what it's like when doves cry.

      --
      --------
      Free your mind.
    3. Re:What about Java/C++ developers by Malc · · Score: 1

      A good programmer experienced in both languages won't have this problem. Of course, if you're using the same classes in both languages (e.g. client vs server), it might be easier not to use templates as it makes converting between the languages quicker/easier, and makes long term maintenance simpler and more reliable.

    4. Re:What about Java/C++ developers by FortKnox · · Score: 1

      I don't write C++ at my job, but I still long for templates.
      Why?
      The model layer that I tie into is very strict on casting, so they force everything into arrays (see my previous entries in this article for arrays vs collections). And being the java coder I am, I much prefer dealing with collections. Templates would make everyones life better if they existed java.

      --
      Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
    5. Re:What about Java/C++ developers by Hard_Code · · Score: 0, Flamebait

      Java will have genericity (i.e. templates) in 1.5, and by all accounts it will be implemented much better than C++ templates (too bad it has taken so long though).

      --

      It's 10 PM. Do you know if you're un-American?
    6. Re:What about Java/C++ developers by dubstop · · Score: 1

      My J-Developer friend was just telling me the other day how he longed for templates in Java.

      Try Pizza. It's got some good stuff in it, and it compiles to byte-code that will run on Sun's JVM.

    7. Re:What about Java/C++ developers by Anonymous Coward · · Score: 1, Insightful

      Whoever came up with the 'templates' in Java understood less than half of what templates are actually useful for. The Java version only addresses the 'cast' situation when retrieving objects from a collection (like the Stack example you'll find elsewhere in this discussion). No provision was made for using templates for policy and that's where the real power of C++ templates is. Other's have mentioned it, but pick up the Alexandrescu book to understand. You'll be amazed.

    8. Re:What about Java/C++ developers by Anonymous Coward · · Score: 0

      Although plans are for Java to get templates, the proposed facility is semantically quite different from the C++ feature (but syntactically, they're clearly C++-inspired).

      In particular, Java templates aren't designed for compile-time expansion: The JVM runs all the instances through a single generic byte-code sequence. This is nice for code-size, but not for performance.

      (I wrote the first author of the book reviewed in the article.)

    9. Re:What about Java/C++ developers by ghum · · Score: 1

      I think it took around 3 generations of C++ Compilers to find the first who did templates correctly.

      Do you really expect that templates will work correctly in Java 1.5?

      Python dynamic typing. Templates for free.
    10. Re:What about Java/C++ developers by dustman · · Score: 1

      Python [python.org] dynamic typing. Templates for free.

      If you think dynamic typing means templates for free, you are confused.

      The whole point of templates are that you get general code (which works on lots of different types) and static typing at the same time. The functional programming community calls this "parametric polymorphism". The C++ community calls this "generic programming".

      Using void* or discriminated unions in C to "hold anything" is a form of dynamic typing. Templates were added to C++ precisely because this approach sucked so much.

    11. Re:What about Java/C++ developers by IWannaBeAnAC · · Score: 1
      Can you provide any details on this? My understanding was that Java generics was essentially a syntactic hack so that you don't have to manually insert casts when using containers, the generated bytecode is identical to the non-generic case.

      This misses 80% of the uses of templates in C++: generic algorithms, traits, compile-time algorithm evaluation etc.

    12. Re:What about Java/C++ developers by ucblockhead · · Score: 1

      I'm a C#/C++ developer, so I'm in pretty much the same boat. When I'm writing C++, I use templates heavily. When I'm writing C#, I bitch and moan about the lack of templates.

      --
      The cake is a pie
    13. Re:What about Java/C++ developers by ShadyG · · Score: 1

      You're absolutely right. I've almost completed the detailed design for a certain type of communications framework, and one of the requirements was that the framework be supplied with as close an API as possible to both C++ and Java developers. Thus the component interface could not make use of templates, or multiple inheritance or anything really that did not cross easily between the two languages.

      Still, in the respective designs for each language, it is becoming more and more obvious that there are many instances in the C++ implementation where the engineer will make good use of templates. In fact, I'm actually leaning toward recommending C++ as the only implementation language in part because of the benefits of templates, and just wrapping it in Java using JNI.

      -- ShadyG

    14. Re:What about Java/C++ developers by angel'o'sphere · · Score: 1

      Thats unfortunatly not the case.

      The Java Generics are no templates, they only look like templates.

      Template arguments are "erased" to java.lang.Object.

      That means List<Strin> is equal to List<Integer> and both are List<Object> ....

      The compiler only checks type savety very limited, in fact you can easyly put a Integer into a List<String>, you only realize on extraction the problem: ClassCastException.

      There are a lot of further problems .... I realy wished there was a C++ to Java Byte Code compiler.

      Seems I have to write my own compiler :-/

      angel'o'sphere

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    15. Re:What about Java/C++ developers by Old+Wolf · · Score: 1

      I can program both C++ and QBasic. (There was a time when I did both). I did not go around writing C++ code like:

      line_10: int i;
      line_20: for (i = 1; i = 1000; i++)
      if (str[i-1] == 'p')
      puts("Found a p");

    16. Re:What about Java/C++ developers by ghum · · Score: 1

      Using void* or discriminated unions in C to "hold anything" is a form of dynamic typing. Templates were added to C++ precisely because this approach sucked so much.

      there is quite a difference between using "void*" for everything and dynamic typing:

      with void the programmer is responsible for checking if the data coming in is of correct type. with dynamice typing it's job of the runtime engine.

      That is quite similiar to "templates", which have to be constructed to "adopt" to different types. And templates are very complicated - as the release of a complete book dealing with them proofes.

  5. Moderators! by FortKnox · · Score: 1

    This is a legitimate question, and shouldn't be modded down. It warrents a good discussion on the topic of templates (which is, in fact, the topic of this review).

    --
    Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
  6. Only when misused by DreadSpoon · · Score: 2, Insightful

    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 you have speed/efficiency/code-size vs. taking 6 years or 6 weeks to code something, and with today's hardware, the later is usually the best choice. Also, templates can be used to generate data, not just code, so where you might have before needed a function call in order to compute a value, a template could turn it into the actual value at compile-time (look at how modern games use templates to generate sin/cos/tan/etc. values for constant inputs).

  7. Templates are the best C++ feature imho....BUT... by fcrick · · Score: 4, Interesting

    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!

    --
    Your signatures belong to me.
  8. What about... by Anonymous Coward · · Score: 0

    "STL Tutorial and Reference Guide -- C++ Programming with the Standard Template Library" by David Musser and Atul Saini (Addison Wesley, 1996)

    It's the only STL book I've ever read, and it's good enough that I have not needed to open it again since I read it the first time. ;)

    1. Re:What about... by stratjakt · · Score: 1

      This book is about defining and using your own templates, not using STL.

      Just like a book about OO design has nothing to do with a book about the MFC.

      --
      I don't need no instructions to know how to rock!!!!
    2. Re:What about... by jdennett · · Score: 1

      "C++ Templates" isn't about using the STL. It's about writing templates, and how they work. It will let you understand how to build extensions to the STL, or how to design its successor, if you make the effort.

      My review is online at http://www.jamesd.demon.co.uk/reviews/c++-template s.txt, if I recall correctly.

  9. Templates and Linked Lists.. by Shant3030 · · Score: 2, Interesting

    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.

    --
    100% Insightful
    1. Re:Templates and Linked Lists.. by Dionysus · · Score: 1

      Because you better understand how a linked list works before you use them. You can't really appreciate std::vector or std::map before you really understand the data structures...

      I can't even tell you how many 'programmers' I know, who don't know the difference between the different datastructures, and therefore choose the wrong container when coding.

      --
      Je ne parle pas francais.
    2. Re:Templates and Linked Lists.. by lazyl · · Score: 1

      You shouldn't really think of them as replacements; they're more like enhancements.

      When deciding which STL containter to use you have to know the underlying algorithim. The STL "set" container is a linked list. You would use a set over a vector in the cases where you need the advantages of a linked list over an array. The map container is a red-black tree; dito there. So, understanding the stuff you used in school is still important; you just don't actually have to implement any of these structures in the real world (very often).

      --
      Aw crap, ninjas!
    3. Re:Templates and Linked Lists.. by rkit · · Score: 1

      Sorry to correct you, but a STL set can not be implemented as a linked list, because it needs log(n) complexity for inserting or removing elements while makin sure there are no duplicates. One way to do this is a red-black tree like a map, but without additional data at the nodes. If you want a container with double-linked list characteristics, there is std::list.

      --
      sig intentionally left blank
    4. Re:Templates and Linked Lists.. by lazyl · · Score: 1

      Opps. Right. Temporary dyslexia there. Thanks for the correction.

      --
      Aw crap, ninjas!
  10. 3D Math by devnull17 · · Score: 2, Interesting

    There is an interesting use for templates in 3D vector math:

    http://www.flipcode.com/tutorials/tut_fastmath.sht ml.

    It's a kludge, but it provides some real performance benefits.

    1. Re:3D Math by Minna+Kirai · · Score: 2, Insightful

      It is by no means a "kludge". The intended use of a tool is never a kludge, even if some people find it personally unintuitive. (The only kludgey thing in that article was the extra magic needed to convince MS VC++ to deal with templates sanely)

      The goal of adding templates to C++ was to provide the same power macros provided to C, but as part of the language, rather than a preprocessor to it. That way, they can be typesafe, produce better error messages, and be more flexible (since templates live inside of namespaces, unlike macros which exist at the parser level).

      C programmers often performed fast math evaluations with macros, so replacing them with templates is simply a natural step.

      However, looking at templates from an entirely different perspective- it is possible to reasonably classify most all uses of templates as "kludges".

      Why? Because they are often used to force an evaluation to happen at compile-time, rather than runtime. But, if compilers made full use of the static program information that is present during compilation, they could determine that many conditional checks are often tautologies, and elminate them from the output code.

      The reason C++ compilers can't usually make these throughout checks is because of backwards compatibility- to support interoperation with other programming languages, individual C++ files are compiled independently and then linked together by a stupider program. The linker has little knowledge of the static program elements, and less ability to modify the output code. So many potentially useful optimizations are impossible- unless the programmer uses something like templates to force them to occur.

      So, from that perspective, it can be argued that nearly every template is a kludge- a workaround for the legacy compiler/linker split. (Many uses of macros were a similar kludge- a way to force an expression to be computed inline, rather than spending a function dispatch on it)

    2. Re:3D Math by Anonymous Coward · · Score: 0

      Interesting points. BTW, proper grammar would be "minna ga kirai [desu, if you're in a formal mood]." (:

  11. template versus derivation by jbert · · Score: 1

    OK. Could someone please offer some informed comment on the following. (thanks in advance).

    If I template a two-argument function in C++ to (e.g.) compare two instances of a class for equality (using the == operator) and print them to an ostream if they fail to match (using the template was actually a class which manipulated objects which derive from a "Listable" interface.

    1. Re:template versus derivation by jbert · · Score: 2, Informative

      [and here's that once again with feeling (and better HTML)]

      OK. Could someone please offer some informed comment on the following. (thanks in advance).

      If I template a two-argument function in C++ to (e.g.) compare two instances of a class for equality (using the == operator) and print them to an ostream if they fail to match (using the &lt&lt operator) [why yes, I was writing some unit testing infrastructure, why do you ask?] then:

      - my template function will fail to compile if called with two instances of objects which lack the == and &lt&lt operators.

      - this is a broadly equivalent approach to defining a virtual base class (java interface) requiring implementation of these two operators and re-writing the template function to take pointers to the relevant base class. Users would need to derive from my base class to call my function (and hence would have to implement those two operators).

      The latter approach (derivation) is more coding for the caller.

      The former approach (templating) requires the coder to inspect my entire template function (or read the Fine Docs) to determine the interface s/he needs to implement to use it.

      Both approaches are compile-time type safe.

      Given that the two approaches are in some sense equivalent, are there good guidelines on when to use derivation instead of templates or vice versa?

      PS. The equivalent for the STL would be that the list&lttype T&gt template was actually a class which manipulated objects which derive from a "Listable" interface.

    2. Re:template versus derivation by arkanes · · Score: 1

      This isn't a templates vrs derivation question, because you're using a template regardless. It's a question of whether or not you want to the requirement that objects being tested need to implement == to be enforced in code or socially. (Well, it's still socially even if you make the VBC, because they just might have not inherited from your class).

    3. Re:template versus derivation by vidarh · · Score: 2, Informative
      I don't really see your particular case as a problem - as you say it is already typesafe, and so a comment at the top of your function "requires type Foo to support interface Bar" would serve the same purpose as what you suggest.

      However if you want more user friendly compiler error messages, that's another matter. A lot of work has gone into "compile time asserts", to catch as many problems as possible at compile time and give more intuitive errorts (in this case you got an error, but consider the problems if the classes supported the operators you needed but made them do something entirely different).

      Instead of deriving, you could for instance check for an enum "supports_someinterface" in the types using a standard assert.

      This allow you to use "assert(Foo::supports_interface_Bar);" in the functions that have specific requirements. Note that the value of the enum is irelevant as long as it's non-null, and since the enum is a constant value known at compile time, there should be no runtime overhead (neither space nor performance) of the assert at all if your compiler is reasonably smart.

      With GCC, this gives me the reasonably friendly error message: "'supports_interface_Bar' is not a member of type `Foo'" instead of (or rather, in addition to) some hopelessly cryptic error message if I try to instantiate a template with the above assert on a type that doesn't have the enum.

      Of course, you might not have the luxury of changing all types you might want to use with your template, and some of them may already fulfill the requirements even if they don't contain the enum.

      Fear not, that's what traits are for. Declare a template. Specialize the template for any type that supports your interface, and instead of "assert(Foo:supports_interface_Bar)", you might do "assert(Supports<Foo>::interface_Bar)" or "assert(Supports<Foo>::requirement_HasOutputOperat or)".

      Strategically placing these at the top of your functions also serve to document the requirements.

      Ok, so I saved the simplest option for your case until last (the above is better suited for complex requirements, not something as simple as "this templates needs member functions A,B and C to be implemented) :

      assert(&Foo::operator<<)

      With GCC, this produces the error message "`operator<<' is not a member of type `A'" if the operator isn't supported. Place asserts covering all the member functions you need at the head of your function and you both have documentation and reasonable error messages.

      The above should have no runtime cost at all provided that the compiler at compile time is willing to guarantee that Foo::operator<< will never occupy address 0. However, don't assume your C++ compiler that smart (GCC 2.96 doesn't appear to be, I haven't checked any newer versions), so one improvement: "assert(sizeof(&Foo::operator<&lt))". sizeof is evaluated at compiletime, resulting in a constant that in this case must be non-null, meaning the assert will neven trigger, meaning the compiler will discard the code (this was enough to make GCC optimize the thing away).

      This leaves us with this nice little macro (who I'm sure someone will find a nasty problem with :-):

      #define REQUIRE_MEMBER(expr__) assert(sizeof(&(expr__)))

      Which can be used like this:

      REQUIRE_MEMBER(Foo::operator<&lt);

      Hot tip: sizeof() is extremely versatile for compile time testing whenever you can reduce the problem to either making code illegal in one case or return a constant expression (which is needed to apply sizeof to it), or when you an reduce a problem into a constant expression that will be a different size (that you can compare with a known quantity) depending on the outcome.

      The book being reviewed contains at least one good example of this.

    4. Re:template versus derivation by Anonymous Coward · · Score: 0

      Requiring users of your function to implement a Listable interface changes the class that they're creating. It's added methods to its definition, it's invasive. It also doesn't work for non-classes, i.e., built-in types which do not implement a "Listable" interface.

      The template version only requires that the classes define an operator== and operator&). Those are hardly difficult requirements as many classes include those operators anyway.

    5. Re:template versus derivation by Old+Wolf · · Score: 1

      Why does the former approach require you to inspect their function?

      All they have to do is look at the compiler message and make sure their object has the relevant operators. After all, if an object is unable to compare itself to others, or print itself on ostream, then it is not suitable for your stated purposes anyway !

      The template method is way better than the derived class method, if you ever need to change something in your code later in time, or port the code elsewhere. Not to mention how inflexible this would be if it were code destined for a library.

    6. Re:template versus derivation by jbert · · Score: 1

      Hmm. I outlined a situation, but didn't really state a question/problem very well. Sorry about that.

      Its more of a design issue.

      Templates "smell funny" because you could end up with arbitrarily complex requirements on the types with which you could use them, requiring code inspection and/or compile/read error/implement new method cycles. That sucks.

      Derivation is cleaner, but it clutters the design. Each class which can run in the test framework would need to implement derive from a "Testable" interface. This is probably correct but a bit of a pain, you could end up deriving a bunch of stuff. Maybe this is where the "mixin" approach pays off.

      I guess I've answered my question. Use templates only in simple cases (if at all) - derivation if the required (implicit) interface is non-trivial (or if you feel like being purist).

      In that respect at least, templates feel more like C macros - you *can* do anything with them, but its a sign that your design is a bit screwed if you go overboard.

    7. Re:template versus derivation by jbert · · Score: 1

      It was a templates versus derivation question. I probably didn't describe it well.

      Intead of a template test function which takes two args of templates type T (which implicitly must implement == and ), the function could be non-templated and takes two pointers to "Testable".

      Testable is a pure abstract base class. In order to use the function with a class, the class must derive from Testable (this imposes the requirement that the functions be defined).

      This gives all the same type checking and is equivalent in many ways. Because it is equivalent, you need to make a design choice on which to use. I was asking for help in making that design choice (but I didn't phrase it very well).

      Note - the test thing is simply a single example. The general question is: "to implement generic functionality, should you write in terms of templates, or require that the users of your generic code derive from some base interfaces?".

      My current position (open to change, please convince me) is that it is a complexity thing. The template approach is suitable for fairly trivial interfaces, but breaks down with a complex interface because the interface is *implicitly* defined in the usage of the class throughout the generic code, rather than explicity in the interface class definition.

      You can address the implicit interface with comments (not assertions), but that requires significant discipline on behalf of code maintainers.

      [You can't use assertions in the generic code to enforce this, because the generic code (by definition!) doesn't have a full picture of the class with which it might be used.]

    8. Re:template versus derivation by jbert · · Score: 1

      I've made a couple of other replies in the thread, which might be of interest, but the point is that in this case a template feels fine.

      In the more general case, you would need to reply on code inspection and/or trial and error compiling to learn the interface you need. (even then it isn't necessarily obvious. Say my template calls a method called "to_string()" on your code, assigning the result to std::string? Should you implement something which returns a string or a const char * (the compiler will be happy if you do either)? Do I do anything odd like call into some legacy routines which implicitly assume that the memory in that std::string has a zero byte after it [hmm...thats where this example probably falls down, since to do that I'd need to call data() rather than c_str() on the string or something, which would be a bug.]

      If the implicit interface the writer of the generic code is using is in terms of a const char *, the null byte will be there.

      The above example isn't perfect, but it tries to make the point that reverse-engineering an interface from reading template code and compiler error messages might not be as trivial as the original example leads you to think.

    9. Re:template versus derivation by arkanes · · Score: 1
      Well, if your template relies on the the objects it's going to be a container for implementing certain functionality, then it's not all that generic - in that case, I'd go with the derivation.

      If you wanted a more complicated, but more extensible solution, your template should include a parameter for equality testing (or whatever), much like the STL set classes do. (It uses the < parameter to sort in a b-tree by default, but you can provide one of your own. Or you can just override < in whatever you're putting in the set).

      It depends on your need, and what you're making. If you're making a package that'd you'd sell or be providing to other people, where you aren't involved in development, you certainly should go with the template - it's silly to expect them to change thier inheritence hierarchy to support you.

    10. Re:template versus derivation by vidarh · · Score: 1
      How does templates "smell funny"? I've outlined several methods for documenting requirements on templates usage that will even trigger nice compiler warnings if you don't follow them. How will that be solved by derivation? You will still need documentation to know what requirements needs to be filled. I'd make the argument that using some of the techniques I outlined could be beneficial when using derivation as well, simply for the reason that relying on a "it compiles, so I've satisfied the requirements" mentality is dangerous when only satisfying a few syntactical constraints will make things compile without any real understanding of what requirements must be filled.

      Compile time assertions can strengthen that a lot. You end up with a compile/edit cycle only if you've actually failed to understand a requirement or failed to comply or indicate your compliance.

      Personally I find using templates a lot cleaner than derivation. Derivation introduce a tight coupling which, like in your mention of a "Testable" interface, is unhealty: Class hierarchies grow and expand for functionality that may be unrelated to the problem domain, and introducing new interfaces may require changes to a large number of existing classes. Templates, used sensibly, allow for much smaller, more cohesive components that can easily be decoupled and reused.

      In general I tend to take a long hard look at class hierarchies that grow above maybe 3-4 levels of inheritance and 10-15 classes total and try to split them up - large class hierarchies tend to make it hard to introduce change. Often such class hierarchies can be dramatically reduced by using templates and policy or traints classes to encapsulate specific parts of the functionality in cohesive reusable components that can be maintained and developed separately.

    11. Re:template versus derivation by Old+Wolf · · Score: 1

      You seem to be complaining about documentation here .. if a function does anything possibly dangerous (eg. assuming \0) you should mention that in the documentation (or arrange that it's obvious from naming or style conventions). But surely this argument applies to both cases. At least with the template you have access to all the code, rather than the derived case where the original code may not even be given (just a header and a library).

    12. Re:template versus derivation by jbert · · Score: 1

      But all template code requires that the object types implement certain functionality, precisely the functionality which the template uses. If a template doesn't call any methods on an object, it isn't really very useful.

    13. Re:template versus derivation by arkanes · · Score: 1

      Not true, actually - template containers, for example, don't require any functionality to be implemented in the object.

  12. One other point by biglig2 · · Score: 3, Funny

    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.

    --
    ~~~~~ BigLig2? You mean there's another one of me?
    1. Re:One other point by ColdForged · · Score: 1
      It is of limited use for those looking for a guid on changing the timing belts in '98 Pintos,


      We should strongly consider bombing Ford Motor Company instead of Iraq if they made a Pinto in '98... that seems a far more insidious threat to me than mere Scuds and the ubiquitous WMD.
      --

      -"I seem to be having tremendous difficulty with my lifestyle." - Arthur Dent

    2. Re:One other point by swb · · Score: 1

      I'm willing to forgive the Slashdot editors for duplicate story postings and the bad grammar and spelling, but I can never forgive them including the idiotic editorializing thats in story submissions.

    3. Re:One other point by revery · · Score: 1

      It is of limited use for those looking for a guid on changing the timing belts in '98 Pintos

      guid??

      Pinto timing belts have a Group User ID?
      or is that a GUI daemon?

      or did you accidentally put a space there by mistake and meant to say guidon, which a according to dictionary.com is:
      1. A small flag or pennant carried as a standard by a military unit.
      2. A soldier bearing such a flag or pennant.

      or you might have meant guide, but then the sentence wouldn't make any sense... ;)

      --

      Was it the sheep climbing onto the altar, or the cattle lowing to be slain,
      or the Son of God hanging dead and bloodied on a cross that told me this was a world condemned, but loved and bought with blood.

    4. Re:One other point by Osty · · Score: 1

      Pinto timing belts have a Group User ID?

      Don't you mean a Globally Unique IDentifier?

    5. Re:One other point by revery · · Score: 1

      There you go, I knew there was a better one I could have used....

      --

      Was it the sheep climbing onto the altar, or the cattle lowing to be slain,
      or the Son of God hanging dead and bloodied on a cross that told me this was a world condemned, but loved and bought with blood.

    6. Re:One other point by biglig2 · · Score: 1

      Obviously I meant Guido, that wll knows South American revolutionary. Only his close friends are allowed to drop the o, and only his deadly enemies are allowed to lower case the g. As you can thence deduce, we have a somewhat confusing relationship.

      --
      ~~~~~ BigLig2? You mean there's another one of me?
  13. No bloat if you design correctly. by Chemisor · · Score: 5, Insightful

    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).

    1. Re:No bloat if you design correctly. by mcgroarty · · Score: 1

      And that's it in a nutshell. STL produces far, far better code in most cases if you use instantiations against void* and create your own inline functions to thunk your kind of pointer into the STL container's void*. This eliminates huge amounts of senselessly redundant code.

  14. No portability info? Bummer. by baxissimo · · Score: 4, Insightful
    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.

    1. Re:No portability info? Bummer. by Eponymous+Coward · · Score: 1

      Unless you are stuck having to compile with an old compiler, I don't think this is much of a concern anymore. Most modern compilers are pretty much complete. Support of the export keyword being the obvious exception but thanks to EDG, that's changing as well. The export keyword is probably a bad idea anyway (look up what Herb Sutter has to say on the subject to see why).

      Luckily C++ is not controlled by a single entity, so you can probably buy a better compiler for your platform if you are unhappy with your current one.

    2. Re:No portability info? Bummer. by Anonymous Coward · · Score: 2, Informative

      (I wrote the book, so I'm hardly objective.)

      We didn't include many references to specific compilers because version change so quicly.

      However, we do point out various shortcomings of compilers (without naming them) and, when feasible, we present alternative programming techniques to work around the limitation. It's certainly not the main emphasis of the book, but you'll find such things sprinkled throughout.

    3. Re:No portability info? Bummer. by Anonymous Coward · · Score: 0

      A few days ago, EDG distanced themselves from Herb Sutter's articles on the C++ standardization mailing list. Sutter is a good writer, but comparing his postings with those of the EDG guys on comp.lang.c++.moderated, I'm convinced that EDG's understanding is a cut above Sutter's.

      The Comeau compiler has support for export, and it seems to work quite well. Vandevoorde gave a talk in NYC recently where he showed ideas to make his implementation even better.

    4. Re:No portability info? Bummer. by IWannaBeAnAC · · Score: 1
      I've read the book (unlike the reviewer, I suspect), and I concur, there is plenty of information on different compiler implementations. The fact that one particular compiler isn't listed in the index is a poor measure.

      Great book, by the way. I found it to be an excellent mix of theoretical style ("this is the current state of the art on now templates work") versus practical tips ("this is what you need to know to write templates successfully").

  15. An excellent book, but be aware by dsplat · · Score: 4, Informative

    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.

    --
    The net will not be what we demand, but what we make it. Build it well.
    1. Re:An excellent book, but be aware by Old+Wolf · · Score: 1

      I'm worried by the reviewer's comment that there are no examples. I hate that stupid backas-naur crap. Can you elaborate more on the books' general technique (how it introduces a topic and how it illustrates it).

    2. Re:An excellent book, but be aware by Garen · · Score: 1

      There are tons of examples. I have the book and the book is loaded with "concrete" examples. It's also kind of obvious who wrote what, because Josuttis' doesn't use much exotic vocabulary, which is nice.

    3. Re:An excellent book, but be aware by dsplat · · Score: 1

      In my comment, I posted a link to the author's archive of all of the example source code. There are plenty of examples. I looked at the online copy. It appears to have some additional code that is necessary for completeness so that it will compile, but wasn't relevant to the points being made in the text. Honestly, I believe the code is much easier to understand with the explanations in the text, but it may give you an idea of the quality of the examples. It think that a number of them are useful as a starting point for a library.

      --
      The net will not be what we demand, but what we make it. Build it well.
  16. Re:Templates are the best C++ feature imho....BUT. by oznet · · Score: 1

    Where can I get the tuple template you speak of?

    I'm interested since I regularly work in C++ and Erlang/O'Caml/SML.

  17. Generics are being added to Java by 200_success · · Score: 1

    Actually, there is a Java Specification Request to add generics to Java, which is essentially adding template capability. The proposal is JSR014.

    With a Java Developer Connection account, you can try a prototype compiler with this capability. It claims to generate code that can run on a standard 1.3 JVM.

  18. Of course not.. by bug_crusher · · Score: 1

    Of course they aren't always necessary, but sometimes they are down right handy.

  19. How redundant are the examples? by stratjakt · · Score: 1

    Here's the problem I have with books like this. The examples are things that already exist.

    C++ (or any OO) books that take you step by step through creating a class CShape, then sublclassing CBox, etc etc... Yeah, I get the principles of inheritance, but trivial examples CShape, CBox etc no doubt already exist in $LIBRARY if they're of any use.

    So my question is, do the examples in this book just spew out stuff thats already in the STL?

    I find that tends to have people reinventing the wheel, writing their own templates for say a stack or queue, because the book taught them to do so, even though it already exists.

    And what of namespaces. Those things piss me off.

    --
    I don't need no instructions to know how to rock!!!!
    1. Re:How redundant are the examples? by Anonymous Coward · · Score: 0

      The book doesn't seem to sell you ready-made components (maybe a little in the last part, but the authors deny that their code is meant for anything but illustration).

      Most of the examples are very short and to the point.

      They talk almost exclusively about templates, but every combination of templates "with something else" seems to be covered. That includes some issues with namespaces.

      Actually, there is an appendix about overloading that has almost nothing to do with templates, but it probably the best (certainly the most detailed) explanation of C++ overloading I've seen.

  20. Which categorizes them... by Chemisor · · Score: 1


    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.


    Which kind of categorizes one with the other :)
    *duck the flamethrowers*

  21. Re:Templates are the best C++ feature imho....BUT. by dalleboy · · Score: 2, Interesting

    Name one compiler that is 100% C++ standard compliant.

  22. The problem with C++... by jackjumper · · Score: 2, Interesting

    IMHO, is that a book like this needs to exist. Templates are *way* too complicated for something that is supposed to reduce complication.

    1. Re:The problem with C++... by Anonymous Coward · · Score: 0

      I have some trouble coming up with a programming language that does not come with documentation or expert-level books...

    2. Re:The problem with C++... by theFlux · · Score: 1

      Computers are supposed to reduce complexity and look at how complicated they are!

    3. Re:The problem with C++... by be-fan · · Score: 1

      It's pretty easy to understand templates without using a book. The actual template mechanism is extremely compact. Fully exploiting the power of templates requires a book. This is the same reason so many books on OO design exist.

      --
      A deep unwavering belief is a sure sign you're missing something...
  23. Closures with tamplates by fdicostanzo · · Score: 2, Interesting

    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.

    Why?

    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 your string implementation, you could reallocate the string results many times.

    However, with template closures, the concatenation would return an object which pointed to the two objects that were to be concatenated. Then the second concatenation would point to that object plus the next string. When the entire object was finally actualized by, say, setting it to a variable or as a function argument, then it would create the final string. It could then gather the lengths of all the strings, create a single result string, and then copy everything into it.

    And it wouldn't look any more complicated than:

    string a = b + c + d + e;

    or whatever and it would still be optimally efficient.

    The big downside is that error messages are all but useless.

    --
    Synergies are basically awesome, and they're even better when you leverage them. -PA
    1. Re:Closures with tamplates by Anonymous Coward · · Score: 0

      I'm not sure "closure" is the right term, but yeah: it's a neat technique (expression templates).

      One of the authors of the book (Vandevoorde) actually was one of the original inventors of that approach (with Todd Veldhuizen).

    2. Re:Closures with tamplates by vidarh · · Score: 1

      What you want are "expression templates" (do a search, or look at Boost) which does what you suggest with plain C++.

    3. Re:Closures with tamplates by fdicostanzo · · Score: 1

      I am familiar with Boost. It may handle the specific example of strings that I give but not the general case that I am trying to describe. STL also offers some generic programming tools.

      For instance, I used the method to implement 3D graphics matrix math to reduce multiplication count by using templates to exploit special cases.

      --
      Synergies are basically awesome, and they're even better when you leverage them. -PA
    4. Re:Closures with tamplates by IWannaBeAnAC · · Score: 1
      "Partial Evaluation" is the term you are looking for, not "closure".

      A closure is (if I understand correctly) like a lambda-expression, where you construct a function as part of an expression. Something like

      foreach(mylist.being(), mylist.end(), lambda(int& y) { y *= 2; });

      Where the function to apply to all elements of mylist is defined as part of the foreach() call itself.

      Interestingly, you can do this in C++ too (after a fashion)! Have a look at boost.org.

    5. Re:Closures with tamplates by vidarh · · Score: 1

      I pointed to Boost because it contains examples of expression templates that illustrate how to achieve what you suggested with standard C++ features. In particular the lambda library illustrate the techniques quite well. Maybe I missed something - looking at for instance the lambda library, which parts of what you suggested do you think wouldn't be implementable using those techniques?

    6. Re:Closures with tamplates by vbweenie · · Score: 1

      ...or you could program in Scheme.

      Don't get me wrong, I find the abuse of marginal features of a language to get it to behave in ways entirely unimagined by the language's original designers a highly worthwhile activity - but not in a production environment. In production, you should stick as far as possible to the best documented and most easily supported and understood features of whatever language your PHB has decided you're using; unless you want whoever has to maintain your code to curse you for eternity...

      --
      Experience is a hard school, but fools will learn no other.
  24. Re:Templates are the best C++ feature imho....BUT. by Eponymous+Coward · · Score: 2, Informative

    Greg Comeau's is pretty damned good. Any compiler built off of EDG's (Edison Design Group) stuff is going to be compliant (including the export keyword)

  25. What I want explained to me... by Lethyos · · Score: 1
    about templates is why this doesn't work:
    /* Foo.h */
    template<class T>
    class Foo {
    public:
    T foo;
    Foo(T);
    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 function `main':
    : undefined reference to `Foo<int>::Foo[in-charge](int)'
    main.o(.text+0x29 ): In function `main':
    : undefined reference to `Foo<int>::getFoo()'
    collect2: ld returned 1 exit status
    I have never understood why this fails. I have had a number of cases where it'd be useful to do something like this, and have already resorted to hard-coding types. Can anyone enlighten me? Is this not yet standardized? Will this every be standardized? I understand that this *may* cause ambiguities, but that would not necessarily be a problem you do not properly overload classes (make sure they have all the operators you use in Foo), but it should be fine for base types (the instantiation should be clearly defined as to what type is used). Or perhaps I do not understand correct use of templates. :-)
    --
    Why bother.
    1. Re:What I want explained to me... by xiox · · Score: 1

      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 definitions... Read the info page for lots of useful information on this.

    2. Re:What I want explained to me... by Anonymous Coward · · Score: 0

      You forgot to pound out the template for Foo. Add the following to the bottom of main.cpp and it should compile without errors:


      template class Foo<int>;

    3. Re:What I want explained to me... by rudedog · · Score: 3, Insightful

      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).

    4. Re:What I want explained to me... by Lethyos · · Score: 2, Insightful

      *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 limited number of classes that while they were similar in nature, did not necessarily lend themselves to inheritance from a super class. Overloaded operators were present to make them act appropriately in an encapsulation (that would be class Foo).

      A more basic example would be a graph implementation. The first time I wanted to do this was for course work. I tried creating a generic node object that could take any types for the key and data, and this is how I approached it (should be fine especially since the node class would have no need to manupulate the data).

      Professor said that this approach created ambiguities, but with a concrete instantiation, I thought the compiler/linker would be able to work it out. Oh well.

      I like how Java has an "Object" superclass to everything. That's solves this issue. As for C++, I guess it's not so bad to have an "Object" class in your project.

      --
      Why bother.
    5. Re:What I want explained to me... by Anonymous Coward · · Score: 0
      You are trying to generate the Functions Foo::Foo() and Foo::getFoo() in the object file Foo.o, but there is nothing concrete in Foo.o. Add
      Foo<int> nada(0);
      int bar = nada.getFoo();
      too Foo.cpp and you will generate the neccessary objects in the object file. This is not useful since you'd have to do this for every type of Foo you want to use. That's why templates need to live in headers.
    6. Re:What I want explained to me... by gwappo · · Score: 2, Informative
      Reason this doesn't work is due to templates working at compile time, and you specify use at linkage. The linker is fully template-ignorant and uses decorated names based on the template instantiation to match up templated code much like they were normal C-style functions.

      So, in other words, while your compiler is chugging along on Foo.cpp - it treats your template functions as Declarations, and won't instantiate the code until it knows what this code should look like (and it won't know this until parameter T is defined!).

      Depending on class T (in this case an int, but say it's something that overloads the assignment operator), the implementation will be made.

      "Doesn't a .h cause bloat in instances of Foo for each .cpp that uses it?"

      Putting this in the header file would cause bloat, but only in your .o/.obj files since the linker will only pick one instance of your templatized Foot and use that to link, the others are ignored

      (much like you can override the library malloc (or any other function) with your own, should you be so inclined).

      "So why don't linkers get smarter"

      Because if you were to put templates in your linker, you're actually postponing compilation into the linker -- in other words, you're doing away your linker and building one compiler that treats everything as "sort of" an include file.

      Still do-able, but problematic for larger projects of a couple of hundred/thousand files.

      Hope that answers the question.

    7. Re:What I want explained to me... by Anonymous Coward · · Score: 0

      As I understand it...
      The trouble is that when Foo.cpp is compiled, the compiler does not understand that you want T=int.
      Some compilers (eg. Sun) will actually do two passes through the code, thus making a note of what instances of T are required.
      For g++, a simple solution is to simply add the following line to the end of Foo.cpp:

      template class Foo<int>;

    8. Re:What I want explained to me... by Lethyos · · Score: 0

      This succeeds if I put that line in Foo.cpp. That's actually not so bad of a solution, putting similar lines in Foo.cpp for every data type I might want to use this for. And of course, it'll fail to link if I mistakenly try to use Foo with a datatype I wasn't anticipating it would use (catch bugs early). It's not perfect, but at least I can keep my conventions fairly clean.

      Thanks for the tip!

      --
      Why bother.
    9. Re:What I want explained to me... by Anonymous Coward · · Score: 0

      This is a common question that's probably been explained in a thousand different ways on comp.lang.c++ (you did try to find the answer there, didn't you?). You will be able to find a clear, concise answer to your question there (groups.google.com), but here's my rather torrid attempt...

      The short answer is:
      The compiler must have access to the complete implementations of your template classes before you instantiate them. In other words, copy all your "foo.cpp" code into the bottom of "foo.h"

      The longer answer is:
      When you compile your 'main.cpp', it sees only the declarations for the template class Foo. When you say "Foo foo = Foo(123);" you are telling the compiler to specialize the class 'Foo' on the type 'int' and invoke it's constructor. But the constructor code is in a different source file "foo.cpp" that the compiler has not seen.

    10. Re:What I want explained to me... by albrecht · · Score: 1
      Here's one way of organizing the code that works with g++. Other compilers have other methods of doing template instantiation so you will have to check the manuals.
      /* Foo.h */
      #ifndef FOO_H
      #define FOO_H
      template<class T>
      class Foo {
      public:
      T foo;
      Foo(T);
      Foo();
      T getFoo();
      };
      #include "Foo.imp.h"
      #endif

      /* Foo.imp.h */
      #ifndef FOO_IMP_H
      #define FOO_IMP_H
      #include "Foo.h"

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

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

      #endif

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

      // optional explicit instantiation for int.
      template Foo<int>;

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

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

      return 0;
      }
      --
      Jonathan Albrecht
    11. Re:What I want explained to me... by Anonymous Coward · · Score: 0

      I suspect a lot of replies will tell you that you should include the contents of Foo.cpp in Foo.h.

      However, standard C++ allows you to get the effect you want just by adding the keyword "export" before the keyword "template" in Foo.h. This is not supported by many compilers yet (but described in great detail in this book), but www.comeaucomputing.com has a fully conforming compiler that will handle it (for about US$50).

      I've had a chance to use the feature recently, and it is very very cool. Almost magical.

    12. Re:What I want explained to me... by Lethyos · · Score: 0

      This is a common question that's probably been explained in a thousand different ways on comp.lang.c++ (you did try to find the answer there, didn't you?). You will be able to find a clear, concise answer to your question there (groups.google.com), but here's my rather torrid attempt...

      I thought it might be a common question, but how exactly does one search for this? What is this called? Google: "some weird C++ template trick" probably would return approximately 3,000,000 links and/or news group postings.

      --
      Why bother.
    13. Re:What I want explained to me... by Lethyos · · Score: 1

      Yikes... export is not even supported in gcc 3.2.3. And 50$USD for a compiler is not so hot when you want to write open source software.

      Is this such a particularly difficult or nasty feature that it's so over-looked in even the most modern compilers? Or is it just disliked for some form or convention reasons?

      --
      Why bother.
    14. Re:What I want explained to me... by Daveed_V · · Score: 1

      (I'm the first author of the book, and one of the 3 engineers who implemented the "export" feature.) The feature is certainly difficult to implement. I think the lack of support was primarily due to the "unknown" factors: "How expensive is it to implement?", "Can it be done at all?" and "Will users care?" So far, we have only proved that it can be done and that for EDG it was fairly expensive to do. I've changed my mind a few times on this topic. In an original draft of the book, there was a long discussion that strongly suggested staying away from "export." However, the more I tried to support that suggestion with examples, the more I found that realistic examples worked very nicely with export, and only truly hideous examples did not (which can hardly be blamed on "export"). As a consequence I started thinking about ways to improve the EDG implementation, and I now think that export could bring to the programmer what many expected it would: Faster build times and "templates in binary form."

    15. Re:What I want explained to me... by IWannaBeAnAC · · Score: 1
      Yes, it is particularly difficult and nasty to implement.

      Apparantly, it doesn't solve the slow compile problem either, it just means the compiler has to spend extra effort to work out where the definition actually resides before it can be instantiated.

      Anyone who's actually used 'export', feel free to correct me of course.

    16. Re:What I want explained to me... by russh347 · · Score: 1

      You can put the implementation of a templated class into the cpp file IF it is explicitly instantiated.

      Add the following to the bottom of Foo.cpp:

      template class Foo;

      Change references to Foo in

      There is a limitation... you cannot instantiate Foo without adding an explicit instantiation for it. For internally used template classes, this is sometimes quite useful.

    17. Re:What I want explained to me... by Minna+Kirai · · Score: 1

      It is quite painful to come across an error message like this. It means that your program is correct, if "program" is defined as "C++ code". But in the broader sense- that the "program" is source code, build scripts, makefiles, and anything else needed to create a working executable- it is not correct. But the error comes not from C++ directly, but from the inadequate support for C++ in your development environment.

      The underlying problem here is that those 2 g++ commands are actually running different programs. The first one is running a C++ compiler, as anyone would expect. But the 2nd call (the one that creates the executable file) is falling through to a linker (ld).

      When C++ was introduced, C compilers were replaced with C++ compilers. But C linkers were basically kept around with few modifications. This was done to allow compatibilty with existing ("legacy") libraries, and other languages (which had all been usinc C linkage as a lowest-common-denominator for multiple-language development). However, the linker's ignorance of C++ template syntax means that not all linkers can cope with things that are completely valid according to the C++ language.

      There are workarounds, of course- and the widespread acceptance of these workarounds as a normal part of building programs is part of the reason we're still stuck with old linkers.

      Here's a page of GCC Documentation on the problem's cause, and some ways to address it. It gives this line of introduction:

      "C++ templates are the first language feature to require more intelligence from the environment than one usually finds on a UNIX system."

      Unless we could someday get significantly smarter linker programs with C++ awareness, and a corresponding minor improvement to compiler software so it can feed those linkers a little extra data, problems like this one won't go away.

    18. Re:What I want explained to me... by Old+Wolf · · Score: 1

      and as long as you remember to not actually include foo.cpp in your project file / makefile !

      If I were to put the implementation separate from the class definition, I'd rather it were in a file with extension other than .cpp (or at least, ssomething like .template.cpp)

    19. Re:What I want explained to me... by HuguesT · · Score: 1

      The `export' keyword was supposed to help with this, but it really doesn't.

      If you think about it, the compiler has to deal with Foo.cpp in a different way as it does with main.cpp. In some sense Foo.cpp cannot be compiled just once. It needs to be reprocessed by the compiler as many times as Foo gets instanciated with different types.

      It is probably possible to do this (treat Foo.cpp differently) but it is a major endeavour, and probably not all that useful.

      It's useful to think of template as advanced macros. As such all of their definition belongs to .h files.

      Note that Java does not deal with templates at all. It does all of its genericity with inheritance and dynamic binding. This works well but carries a run-time cost. Like you mention, you can do the same thing in C++, and you will incur the same cost as with Java.

      Templates solve a different problem, the one when the run-time efficiency is paramount.

  26. Re:Templates are the best C++ feature imho....BUT. by Anonymous Coward · · Score: 0

    I haven't had any trouble using templates in VC++.

    I don't do the bulk of my work in C++, but what exactly do you claim prevents templates from working?

    Is it just that one piece of tuple code you found? Perhaps the problem is the code itself?

  27. Extensive template use is dangerous by mcgroarty · · Score: 4, Insightful
    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!

    1. Re:Extensive template use is dangerous by Anonymous Coward · · Score: 1, Informative

      What development environment are you using?

      All the ones I use do work transparently. Certainly, my debuggers demangle the names on the fly (I need extra effort to find the mangled name) and stepping simply steps through the generic code (or specialization if applicable).

      This has been like that for at least 5 years.

    2. Re:Extensive template use is dangerous by rikkus-x · · Score: 1
      Names are mangled beyond recognition for anyone not using a 500 column display or lots of scroll bars.

      Presumably these are the same people who've never heard of typedef.

      Rik

    3. Re:Extensive template use is dangerous by Anonymous Coward · · Score: 0

      which environment are -you- using???

    4. Re:Extensive template use is dangerous by mcgroarty · · Score: 1
      Presumably these are the same people who've never heard of typedef.

      That helps out with writing code, but the link names and the names you see in the debugger (gdb, VS6 and CodeWarrior at least) are still blown up.

    5. Re:Extensive template use is dangerous by bartok · · Score: 1

      Templates and the STL are implemented in GCC and GCC is ported to all the platforms I know of. It's the lowest common denominator of C/C++ compilers.

    6. Re:Extensive template use is dangerous by Anonymous Coward · · Score: 0

      well trolled, sir!

    7. Re:Extensive template use is dangerous by russh347 · · Score: 1

      Like any tool, incorrect use of templates is dangerous. I have a chain saw at home that I won't let my 12 year-old use for that very reason.

      Debugging poorly designed and poorly tested templated code is difficult to deal with. Design it properly, test it thoroughly, and its much easier.

      Explicit instantiation can sometimes be used to reduce compile times and establish control over which template instantiations are actually available.

      Templates are not the silver bullet for every problem. They can be overused, abused. However, when you need them, they can be amazingly helpful, just like the chain saw.

    8. Re:Extensive template use is dangerous by Anonymous Coward · · Score: 0

      Take a look at VS.NETs error reporting, I think it's pretty good. Not perfect, but good nonetheless.

      I've also seen perl scripts which "decipher" the output from gcc and VC6. I dare say the output from that script is perfect. If I could only remember the name of that script. I'm sure if you google for it, you'll find it. I highly recommend it if you're using VC6 and/or gcc.

    9. Re:Extensive template use is dangerous by Old+Wolf · · Score: 1

      Presumably, you are the sort of person who does not know that much about what goes on 'under the hood' in C++ (therefore, a bad C++ programmer) ...
      look up 'name mangling' next time you read a C++ manual.

    10. Re:Extensive template use is dangerous by be-fan · · Score: 1

      You're thinking of this.
      I haven't used them myself, but then again, GCC 3.2.x's STL error messages are generally quite good. Not EDG quality, but pretty good. Certainly not as bad as the Visual Studio 6 crap that seems to have scared many people away from advanced C++.

      --
      A deep unwavering belief is a sure sign you're missing something...
    11. Re:Extensive template use is dangerous by Garen · · Score: 1

      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.

      I can rebuild the entire repository of boost which is oogles of templates in about 1 minute. I don't think compile time is a serious problem, but using templates can include a ton of code, which is what can make templates so useful IMO -- you can chain together huge links of common code, and as a side-effect, the compiler has access to a lot of information. So it's no wonder such efficient code can be generated by using them; it's almost like using global optimization.

      With subtly improper use, templates can bloat code size astronimically and create horrendous execution bloat.

      You must be using a crummy compiler. It's also well known in the C++ community that templates can generate incredibly efficient code. Ever heard of POOMA? Blitz++?

      Let me repeat: development tools HAVE NOT CAUGHT UP WITH C++ TEMPLATES.

      What are you using? MSVC 6.0? If so then it's no surprise, MS has been a huge laggard and notoriously shitty in this area -- 7.0 and 7.1 work great. G++ has also been pretty good since 2.95, which was released in 1999.

      Then there's Intel's ICC, which is outstanding. Metroworks latest compiler is also reportedly pretty good, judging by boosts tests it's way up there iirc.

      There is no debugger available which makes templates as transparent as normal code, inline functions or even #defines.

      Templates and inline fcns or #define's aren't comparable.

      My suspicion is that you've had a really crappy time with some old/crappy tools which have colored your p.o.v.

  28. Re: Put templated code in the .h file by bunratty · · Score: 1
    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!

    --
    What a fool believes, he sees, no wise man has the power to reason away.
  29. Re:Female pronouns by Anonymous Coward · · Score: 0

    And sorry, I don't like double-think, so I'm attacking you for it. Nobody talks like that in normal conversation. It's a middle-school English teacher grammar meme. A virus.

    I suggest you keep your single-think mind onto the subject, which is C++ templates.

    There is no such thing as a 'generic programmer'.

    Generic programming, on the other hand. Mmmm. Vastly underrated.

  30. Re:Templates are the best C++ feature imho....BUT. by BenBoy · · Score: 1

    VC8 is said to be quite std's compliant. Coming soon ...

  31. Meyer has the answer by sellout · · Score: 1

    To get a good background in OO concepts, like generics (templates in C++), Bertrand Meyer's Object-Oriented Software Construction is what you need.

    It's practically required reading to understand OO, and it explains, among other things, why a language with a single eventual superclass (like Eiffel, as well as Java) also needs generics.

    And, as much as I reminisce about C++ and remember using the STL and other templates (my first taste of generics), its implementation of them is pretty bad. So, don't think that it's an "evil" necessary or un, having only seen them in that language.

    --
    "Whatever can go wrong, will." --Finagle's Law
  32. Templates are a crutch by pclminion · · Score: 4, Interesting
    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.

    1. Re:Templates are a crutch by Anonymous Coward · · Score: 0

      If you are referring to using C-based OO or rather component oriented programming I agree with you. There are others out there who subscribe to that philosophy. We are building a code base using void *, properly architected and the results are amazing. The code is 100% generic, reusable, portable and unnaturally fast. It is a perfect mix of power, flexibility and simplicity. We have not had the so-called type safety issues that most people who dismiss this technique complain about. And best of all, the code is coherent, easily maintained and enhanced.

      As for templates, I experimented with and found them more complex than useful. We've replicated most of their capability using older, simpler techniques.

      But to each his own I guess.

    2. Re:Templates are a crutch by Anonymous Coward · · Score: 0

      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...
      The secret here is not cute little language features, but discipline and correct design.


      Wrong. There are programming paradigms, and there are programming languages. A computer language can support, to various degrees, a particular programming paradigm. You claim that built-in language support for a programming paradigm (e.g. using templates for generic programming, or using private data for encapsulation as required by object-oriented programming) is a "crutch." By this argument, anything above machine code is simply a crutch, because programming "discipline" could also achieve the same result.

      The company I work for [makes] products written entirely (ok, 99.9%) in C ... "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.

      Read your own quotation again. By writing only C, your mindset has become limited to believing that C and discipline are adequate for any programming paradigm. This is simply not the case. Incidentally, the quotation is by psychologist Abraham Maslow, and correctly reads "If the only tool you have is a hammer, then you tend to see every problem as a nail." Stop trying to see every problem as something that should be written in C. Those language constructs that you view as "crutches" are cornerstones of different programming paradigms. Different paradigms require different tools. You could compute the value of Pi in Roman numerals, but why would you want to?

    3. Re:Templates are a crutch by pclminion · · Score: 1
      By this argument, anything above machine code is simply a crutch, because programming "discipline" could also achieve the same result.

      Yes, I also said there is nothing inherently bad about a crutch as long as you apply it where appropriate and not when it isn't the right solution. I do view HLLs as a crutch, and yes I've programmed in assembler before. HLLs are a crutch I'm grateful to have.

      Read your own quotation again. By writing only C, your mindset has become limited to believing that C and discipline are adequate for any programming paradigm. This is simply not the case.

      First off, I think I misphrased that slightly. What I meant is that we have products which are 99.9% C code. We also have other products in other languages, as the situation warrants. We use C++ when we should, and PHP when we should, etc.

      But the claim that C somehow can't accomplish everything is kind of silly. It may not always be the best choice (although it often is) but it is never impotent. If you could come up with a problem that is *impossible* to solve in C I would be very interested to hear about it.

    4. Re:Templates are a crutch by Old+Wolf · · Score: 1

      Templates are safer than (void *) casts :)

      Working in an environment where I often have to code an application in C for an embedded environment, then code the same application in C++ in Windows, I invariably do the C++ 'from scratch', using C++ features and the Windows API.

    5. Re:Templates are a crutch by DaveWhite99 · · Score: 1

      Not all templates are crutches. STL, as far I can tell the last 2 years of using it, is extremely useful and efficient. I've never had to write another container since using STL. Assuming you have a half-way decent compiler, STL should definately be in your toolbox. It ain't no hammer, either.

      --
      Biodiesel : domestic, renewable, clean, and in the fuel tank of my bone stock 2002 New Beetle TDI
    6. Re:Templates are a crutch by be-fan · · Score: 1

      Actually, there is one key thing that templates can do that nothing in C can: code generation. Templates can allow you to generate type-safe, generic classes (particularly data structures) well-optimized to the actual data type they contain. Aside from hand coding multiple implementations for different data types, or losing type-saftey by using void pointers, you just can't do this in C. Ditto for stuff like design patterns implemented as templates or a number of other powerful techniques. Read Modern C++ and take a look at some of the modern C++ websites (especially Boost).

      --
      A deep unwavering belief is a sure sign you're missing something...
    7. Re:Templates are a crutch by Pseudonym · · Score: 1
      But the claim that C somehow can't accomplish everything is kind of silly. It may not always be the best choice (although it often is) but it is never impotent. If you could come up with a problem that is *impossible* to solve in C I would be very interested to hear about it.

      That's not what the anonymous poster said. They said that C and discipline are not always adequate. C can accomplish anything in the same way that it's possible to use Roman numerals for any number-representation task. That doesn't mean it's an adequate solution. If it costs significantly more to develop the same product for equivalent robustness, performance and functionality in C compared to C++ (or PHP, or whatever), then C is not a more appropriate tool. If it costs prohibitively more, then C is not an adequate tool.

      The problem is that there are no good studies which compare the effect of language on development sufficiently to convince everyone, so it's all down to extrapolation and anecdote. There are studies, for example, which show that an average programmer produces so many KLOC per year no matter what the language used, and since 1KLOC of C++ generally does more than 1KLOC of C, C++ is more productive. There are small-scale studies which seem to show that the higher-level the language, the faster you can produce a working product. However, nobody has yet tried getting multiple development teams to develop a medium-to-large scale product in more than one language and see what happens in terms of robustness, efficiency, functionality and development cost.

      Speaking from my own experience, I find people using the same arguments against C++ that I used to use... until I actually worked on a large system written in C++. Now I always choose C++ over C unless there is a very compelling reason to do so, like binary compatibility with a legacy system.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
  33. C++ Template Strength by Lailyx · · Score: 2, Interesting

    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 be done in the compilers. Certain compilers in the past have had problems with them (hopefully they're fixed now), and errors in templated code are cryptically reported -- which always confused me. If compilers mangle a name to get the templates to compile, why can't they unmangle the name when reporting errors?

    ------------------
    Lailyx -- Karma's overrated.

    1. Re:C++ Template Strength by Daveed_V · · Score: 1
      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.

      The standard only suggests a specialization for std::vector<bool> and this is now seen by most of the standardization committee as a poor decision.

      But you're right: The possibility for an implementation to transparently partially specialize the pointer case (and other cases) is very useful.

  34. One note... by Lethyos · · Score: 0

    This question is being asked in a sort of "offtopic" way. Sort of a "while we're on the subject" kind of thing. I haven't yet looked at this book yet, but based on some of your comments, I really ought to. Thanks for the replies nonetheless. :-)

    --
    Why bother.
  35. Templates ARE necessary. by PerlPunk · · Score: 1

    I work in a Java shop that has inherited a huge legacy C++ system, meaning we still have to do a lot of maintenance in C++. In order to get by coding in C++ with the same ease as we do in Java, the STL is a necessity--especially when working with collections.

  36. templates are not just for fancy containers by Anonymous Coward · · Score: 2, Interesting

    It is tempting to think of templates as just a fancy way to make a list of addresses (i.e. list) without having to do any casting. But templates let you do much, much more than that- It adds another tool to the programmers' arsenal by allowing him/her to decouple different parts of a program in order to improve its design. This new technique is called "Generic Programming" and C++ programmers like to think of it as being "orthogonal" to other ways of programming.

    The first dimension of program design is to break code into procedures that can be called from several different places cleanly and transparently. This is what C and procedural programming made possible.

    The second dimension is to have a type system that can channel the program to the correct code indirectly, either dynamically through OO polymorphism or statically through function overloading. This was what object-oriented programming and early C++ made possible.

    The third orthogonal dimension is generic typing, or templating- Using this technique, new computer code can be created in a safe manner during compile time that allows abstractly-written pieces to be stuck together arbitrarily as needed to generate new code. All of these pieces have to fit perfectly in order for the compiler to accept it. If the pieces don't fit together perfectly, the programmer has many types of "glue" available (such as function adaptors, or iterator adaptors, etc.) to make them fit perfectly. If the glue isn't 100% perfect, the compiler lets you know and you can correct it. It can be a beautiful way to program if done correctly!

    It also lets people program in a "functional" style, which was originally invented by LISP programmers, and is a great way to glue together abstract objects with abstract alorithms, without having many unsafe local variables. An example is "currying", where a function taking two parameters can be changed to require only one:

    int multiply(int a,int b)//a function that multiplies two numbers
    {
    return a*b;
    }
    int(*x)(int)//x is a function that accepts only one number!

    x=boost::bind(&multiply,2,_1);//set x equal to a newly created "version" of the multiply function that requires only one number- A function requiring 2 numbers now only requires one, without a local variable needed!

    int y=x(3); //y is now equal to 6

    Another functional programming principle that is now possible is to write all your functions to use iterators, which are basically pointer-like objects that can point to anything: lists, arrays, stacks, almost anything! So to multiply all numbers together in an unknown(!) data structure you can write:

    templatemultiply_all(T i,T iend) //i and iend are "iterators"
    {
    T::value_type x;
    while(i!=iend)
    x*=i++;
    return x;
    }

    If you begcome comfortable with thinking of all your data manipulation tasks in terms of iterators and use templates, a whole new world of programming techniques opens up to you!

    1. Re:templates are not just for fancy containers by Anonymous Coward · · Score: 0

      darn- the template tags got garbled- here's the full second example:

      template<class T>multiply_all(T i,T iend) //i and iend are "iterators"
      {
      T::value_type x;
      while(i!=iend)
      x*=i++;
      return x;
      }

  37. Re: Put templated code in the .h file by robertchin · · Score: 1

    Technically, you should be able to put it in the .cpp file, as per Stroustrup's book. gcc does properly implement templates (I should say, does not fully implement), but if you use something like Sun or Microsoft's compiler, it works correctly. Note that this is not an endorsement of Microsoft's compiler.

  38. Standard C++ with STL is the best abstract machine by CodeArt · · Score: 3, Interesting

    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.

  39. Re:Bloat: O.K., I'll bite by renehollan · · Score: 4, Informative
    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.

    --
    You could've hired me.
  40. Re: Put templated code in the .h file by Anonymous Coward · · Score: 0

    Have you actually read the book?

    Chapter 6 "Templates in Practice" is almost entirely devoted to this particular topic (and it's the first time someone actually explains the details of "export" in print).

  41. check out the lambda library in boost by Eponymous+Coward · · Score: 1

    Nice to see the example using the boost library. That library rocks! The Lambda library stuff is very cool as well.

    1. Re:check out the lambda library in boost by Anonymous Coward · · Score: 0

      Its a pity that VC++ cant handle some of it.

  42. Blurb from the back cover: by Hubert_Shrump · · Score: 0, Troll

    It's the number one book for Earth-bound English-reading carbon-based humanoids on the subject of the C++ computer language in the area of template mastery with a pre-requirement of better than average C++ language facility!

    --
    Keep your packets off my GNU/Girlfriend!
  43. This review isn't very good by IWannaBeAnAC · · Score: 2, Interesting
    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.

  44. Re:Templates are the best C++ feature imho....BUT. by gooser23 · · Score: 1

    It's probably something to do with the 'export' keyword. Microsoft's C++ compiler simply does not support it.
    The problem is that you cannot have a template definition seperate from its declaration (ie, you can't put the prototype in a .h and the implementation in a .cpp as you normally would, say with a class. There are ways around this, but they suck.) This is because every time you make use of a template, the compiler needs access to its implementation details. See the chapter on templates (13, I think) in 'The C++ Programming Language', 3rd ed, Bjarne Stroustrup.

    --
    "Dying tickles!" -- Ralph Wiggum
  45. Re:Templates are the best C++ feature imho....BUT. by Anonymous Coward · · Score: 1, Informative

    Comeau C++ is standards compliant. Most compilers based off of the EDG front-end are very compliant. This includes Intel, Comeau's and SGI's C++ compilers. It does not include MS C++ 6 or Sun's C++ compiler, and look at how standards-compliant those are (on the other hand, Borland's compiler is quite good and it's not EDG-based).

  46. Next on my list by CheesyMoo · · Score: 1

    I'll pick up a copy as soon as a debug my long 'Hello, world!' app. Man this thing is a monster, it takes up about 1KB! I think I can shave some off, I'll leave off the ' endl;' and maybe delete some white spaces...

    1. Re:Next on my list by sir99 · · Score: 1

      Here ya go. A 45 byte executable. Although it's not written in C++, and it's not quite at the "Hello, world!" level of complexity ;)

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
  47. Spirit - a lex/yacc written in C++ templates by truth_revealed · · Score: 2, Informative

    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
    >> *( ('*' >> factor)[&do_mult]
    | ('/' >> factor)[&do_div]
    );
    factor = lexeme_d[(+digit_p)[&do_int]]
    | '(' >> expression >> ')'
    | ('-' >> factor)[&do_neg]
    | ('+' >> factor);
    }
    rule<ScannerT> expression, term, factor;
    rule<ScannerT> const& start() const { return expression; }
    };
    };


    This is truly a testimony to the power and expressiveness of C++ operator overloading and templates.

    As an aside, Perl6 is slated to have lexer/yaccer rule syntax built into the language itself. It's really an exciting time for users of computer languages.

    1. Re:Spirit - a lex/yacc written in C++ templates by __past__ · · Score: 1
      Impressive. Even if I hear lots of people cry "operator abuse", in this case the result (or you example anyway) looks quite OK, given that C++ was so not designed to embed DSLs without a preprocessor. It raises the question, however, is there a sane way to debug this?

      It's really an exciting time for users of computer languages.
      If you like that kind of stuff, you should check out Lisp macros in a spare minute. Lispers basically build DSLs all the time - the usual way of programming is to modify the language until it is exactly the right tool for the job. (And, like you example, this is completly portable). Some examples are various Prolog implementations, or CL-XML that compiles its parser directly from eBNF. You can completly redefine the Syntax, things like implementing control structures (like "while" or loops, for example) are trivial.

      A very good (free) book on this topic, although not dealing too much with custom syntax, is On Lisp by Paul Graham, the Bayesian spam-filter guy.

  48. Instantiation mechanism by den_erpel · · Score: 1

    I will probably buy this book.

    I started off with templates (when I moved from C to C++ for system level exploration) and found them to be an annoying evil for the restrictiveness of void use in C++ as compared to C.

    However, I had to come along when I discovered mixins :) You basically create a class without knowing what the parent or the child will be. The advantage is, that it allows for quick and modular implementation.

    A small example. A house is built from a cellar, a number of levels and a roof.

    In order to implement a 1-level house you define:

    class SimpleHouse<Roof<Level<Cellar> > >{};
    if you want a more levels
    class HighHouse <Roof<Level<Level<Level<Cellar> > > >{};

    That's all folks, methods etc, defined by the template instantiation, ...

    This example might be pretty silly ,but I think it gets the point accross. For a good use of these misins, look for 'heaplayers' on google (though the code is a bit buggy by times, but since everything is working via template instantiation, it's hard to debug and bugs only pop up when the become instantiated.). It would be nice is this is covered :)

    What I do want to know, is what exactly this is doing to my code bloat X)

    --
    Genius doesn't work on an assembly line basis. You can't simply say, "Today I will be brilliant."
    1. Re:Instantiation mechanism by Anonymous Coward · · Score: 0

      How is the following useful?

      class HighHouse <Roof<Level<Level<Level<Cellar> > > >{};

      Don't you have to give those 3 Levels names if you plan to use them in code? Otherwise how would you access level 2? Please explain why this is saving you programming effort.

  49. Genetic programming by iamacat · · Score: 2, Funny
    Wouldn't this be a good term when someone is thinking about programmers gender or race when reading a technical article?

    I use she because women (and some men!) get all offended if I use "he" as a generic pronoun. I couldn't care less myself, so fine, have it their way. Besides... ladies first! At least when it's this easy. I don't think most people have mental images of every word they say/hear. Otherwise, how can you stand walking around at work hearing things like "you screwed my PC", "this code kicks ass" and "I have to remove all the bugs from this piece of shit today"?

    1. Re:Genetic programming by Henry+V+.009 · · Score: 1

      Heh. As you can tell, offending people doesn't bother me. But, if you'd like, I'll make it a point to be offended if you use 'she' as a pronoun in a technical paper I read. That way you can just write what you feel like writing, cause it's definitely gonna offend somebody.

  50. Low Level by Anonymous Coward · · Score: 0

    ... ah, for the old days when I had to defend C++ as not too high level, not too bloated, etc.

    Oh no, now it's "low level" and fraught with scary difficulties.

    Guess what, you don't have to use pointers if you don't like! There are these things called class systems and they can even do amazing things like "garbage collection", although those are more trouble than their worth.

    Now C++ is just for systems programming. Oh yeah, and any other program you want to be efficient.

    -C++ Troll

  51. Bloat is Good by exp(pi*sqrt(163)) · · Score: 1
    You're trolling but I'll bite anyway.

    Sometimes using templates does generate vast amounts of code. But guess what! Sometimes you want vast amounts of code. Templates allow you to build complex algorithms that get bound together at instantiation time. You only have to write the small pieces and the complexity gets built by the compiler for you. You can end up with a usefully complex piece of code that's easy to develop and easy to maintain. Without templates in C++ you have to resort to subterfuges like macros to build complex pieces of code at compile time.

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
  52. Templates allow you to push some of the work... by exp(pi*sqrt(163)) · · Score: 1

    ...of your code into the compiler making the run time faster. Here's an extreme example of what I'm talking about.

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    1. Re:Templates allow you to push some of the work... by sir99 · · Score: 1

      Rats; based on the link, I was hoping it would generate a Peano (plane-filling fractal) curve. The scary thing is, I think it could actually be done with C++ templates.

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
    2. Re:Templates allow you to push some of the work... by exp(pi*sqrt(163)) · · Score: 1
      You could easily write a space-filling curve function - it just wouldn't actually have an I/O :-)

      That code is named after Peano's axioms for arithmetic.

      --
      Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
  53. Re:Templates are the best C++ feature imho....BUT. by gkatsi · · Score: 1

    www.boost.org
    The documentation for the tuple library is here

  54. You are right... by Anonymous Coward · · Score: 0

    I am a Microsoft employee and I can tell you that Microsoft's implementation of templates is so flaky, no Microsoft developers use templates in house. That's right - Microsoft doesn't trust it's own implementation of templates enough to use them.

    This is obviously a huge loss for the developers because templates are one of the best things in the C++ standard library - when properly used. For anyone who hasn't used templates, I urge you to give them a try. No one I know who used templates once has ever wanted to go back.

    Posting anonymously for obvious reasons.

    1. Re:You are right... by WildTurk · · Score: 1

      As someone who has had to use templated code in many a port, I would never ever advocate using templates. If you say that you need to use templates then you don't understand OO. If you say you actually like using templates well that you don't understand programming. If you say that templates work across compilers then you are insane!

      As has been mentioned templates are evil, exorcise them from all code. Now!

      --
      Life is like gravity. It sucks you down.
    2. Re:You are right... by Interrupting+Cow · · Score: 1

      Are you a troll or just a moron?

      --
      in terminus illic est tantum opes
    3. Re:You are right... by Anonymous Coward · · Score: 0

      Amen brother.

  55. Re:Bloat: O.K., I'll bite by Q+Who · · Score: 1

    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>);
    }

    So, you have just slowed your sort template by an order of magnitude, since you use a function pointer to compare elements, something that would be probably inlined by the original template.

    Best of both approaches? I don't think so...

  56. A C++ book by Voldemort??! by AlphaMaker · · Score: 1

    Apparently, the evil one is branching out...

    1. Re:A C++ book by Voldemort??! by Daveed_V · · Score: 1

      Darn. And I thought that hiding under a Belgian surname was a good idea. -YKH

  57. vector == bad by Vigilante42 · · Score: 1
    While I fully agree that templates in general are a Good Thing, the current bool vector is not one of them.
    • It does not meet the container or sequence requirements
    • ::iterator does not meet the requirements of a forward, bidirectional, or random-access iterator
    • It assumes space requirements takes precedence over speed requirements. Not necessarily true.
    • The name is misleading since the storage is not bools

    Basically the current bool vector should be depreceated as soon as possible.
  58. Way to guarantee you pop an int. by Anonymous Coward · · Score: 0

    Only push ints.
    Duh.

    Garbage collection is cool; unless you dont'
    write garbage code.

  59. The 'export' keyword is a failure by rogersc · · Score: 1

    When the experts cannot figure out how to use the export, that tells you something. What is does is very subtle and complicated, and hardly anyone understands it. It appears to be a major C++ design mistake.

    1. Re:The 'export' keyword is a failure by Anonymous Coward · · Score: 0

      Anyone care to comment on these subtleties?

    2. Re:The 'export' keyword is a failure by sir99 · · Score: 1
      I don't think export is very hard to understand. It's apparently just really hard for compiler writers to implement. Example from Stroustrup's book (fair use, baby!):

      // file1.c:
      export template<class T> T twice (T t) { return t + t; }

      //file2.c:
      template<class T> T twice (T t); //declaration
      int g (int i) { return twice(i); }

      At this point you are supposed to be able to compile file1.c and file2.c separately, and have it all work. Easy for the programmer, hard for the compiler implementor.

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
  60. Re:Bloat: O.K., I'll bite by renehollan · · Score: 1
    So, you have just slowed your sort template by an order of magnitude, since you use a function pointer to compare elements, something that would be probably inlined by the original template

    Yes, but I was addressing the use of templates to hide downcasting and still use common backend implementations, increasing type-safety. I briefly hinted that this does not add anything over the classic generic C solution. Obviously templates can help us do better than this, a lot better, for the reason you note.

    In practice, we'd probably specialize Sort() for the types of interest:

    void Sort(int array[], size_t count)<int>
    {
    InlineCompareSort<int>(array, count);
    }

    In fact, using type traits (see Alexandrescu's "Modern C++ Design"), we could have Sort use a SortImplementationTrait<T> class template and automatically generate an inline comparison or external comparison function version, based on the SortImplementatioTrait of the type being sorted (vis. SortImplementationTrait<T&gt>::Inline). That's probably what you were thinking of. If you want, I could flesh out the design for you (hint: Partial template specialization on the type trait makes it easier.)

    But, that gets us far from the aspect of the original concern that I chose to address: encapsulation of downcasting within templates to enhance overall typesafety of code.

    --
    You could've hired me.
  61. Yes. Templates are not macros by Animats · · Score: 1
    It's possible to do arbitrary computation at compile time by abusing the template system. Don't.

    Templates as a way of building code that can be instantiated for various types are great. Templates used as a general-purpose programming language suck. You create all the problems of LISP macros, and with far less debug capability.

    1. Re:Yes. Templates are not macros by Greyfox · · Score: 1

      Aww! But I really want to implement a compile time matrix multiply...

      --

      I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    2. Re:Yes. Templates are not macros by mcgroarty · · Score: 1
      Aww! But I really want to implement a compile time matrix multiply...

      We had a guy using templates to convert quaternions to matrices at compile time. Your joke did not make me laugh! :(

    3. Re:Yes. Templates are not macros by Tiny+Elvis · · Score: 2, Insightful

      What problems of Lisp (Common Lisp?) macros are you talking about?

    4. Re:Yes. Templates are not macros by OneEyedApe · · Score: 1

      The problems which arise from someone not fully understanding what they are trying to use. I've been trying to teach myself Common Lisp, and one thing I've noticed is that CL macros are extremely powerful, but also quite complex, and if not implemented properly, they can cause a host of strange errors.

      --
      Life sucks, but death doesn't put out at all....
      --Thomas J. Kopp
  62. Oops, (use preview, use preview, use preview, ...) by russh347 · · Score: 1

    You can put the implementation of a templated class into the cpp file IF it is explicitly instantiated.

    Add the following to the bottom of Foo.cpp:

    template class Foo(int>;

    There is a limitation... you cannot instantiate Foo without adding an explicit instantiation for it. For internally used template classes, this is sometimes quite useful.

  63. You lost me. by MisterFancypants · · Score: 1
    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.

    So what the fuck IS the book for, if not to learn about templates?

    1. Re:You lost me. by Anonymous Coward · · Score: 0

      He does not care what the book is about, does not care c++, as long as he's got java trash and freaky games to take care of on fcuking MacOS

  64. I call bullshit by MisterFancypants · · Score: 1

    Sorry, the Microsoft VS 2003 (currently in beta for marketing reasons, though the code is really finalized) C++ compiler is THE MOST standards compliant C++ compiler you can get after Comeau C++. It supports every feature, with rock-solid stability, except for the 'export' keyword, which is useless anyway. And unlike Comeau C++ it can be used to generate real-world optimized code.

    1. Re:I call bullshit by be-fan · · Score: 1

      A) Calling VS 2003 "THE MOST standards complient" is bullshit until it's actually released. I hear its good, but better than GCC or Intel C++ 7.x? The community will decide that, not Microsoft's marketing department.
      B) The 'export' keyword is not useless just because VS 2003 doesn't support it. It's certainly rather limited in its usefulness, and I've only really wanted it a couple of times, but it's not useless.
      C) Comeau uses the platform's native C compiler to actually generate code. It can use gcc (very good code generation in the 3.2.x series), or Visual C++ 7.0 and a number of others).

      --
      A deep unwavering belief is a sure sign you're missing something...
  65. Re:Templates are the best C++ feature imho....BUT. by Anonymous Coward · · Score: 0

    spoken like a true Microsoft drone.

  66. Re:Congressman Boucher sells out! +1, Patriotic by Anonymous Coward · · Score: 0

    he's leaving the door open for turkey to take over the kurdish lands!

    Now, now, it's not nice to call GWB a turkey!

  67. Re:Templates are the best C++ feature imho....BUT. by Old+Wolf · · Score: 1

    I've never had any problem with Borland's compilation of templates. Have you given C++Builder a try instead of VC?

  68. Re:Templates are the best C++ feature imho....BUT. by fcrick · · Score: 1

    try the following:

    1. code up something using STL classes other than the ones i've mentioned, and then try to do something meaningful - they just won't compile.

    2. try virtually any of the moer advanced templates of boost.org, a great site for templates. VERY few lack the note 'won't work with microsoft'

    --
    Your signatures belong to me.
  69. Re:Next on the bad coder's list by Old+Wolf · · Score: 1

    template void print_hello_world(void)
    {
    printf("%c%c%c%c%c w%cr%cd\n", a, b, c, c, d, d, c);
    }

    int main(void)
    {
    print_hello_world();
    return 0;
    }

  70. Some articles I wrote on C++ by MichaelCrawford · · Score: 1
    If you're a C++ programmer, you might enjoy reading the following articles which I wrote:

    Thank you for your attention.

    --
    Request your free CD of my piano music.
  71. Re:Next on the bad coder's list by Old+Wolf · · Score: 1

    Man.. i've been sitting here all day thinking how dumb those people were that screwed up their code cos they didn't preview , and then I do it myself :) Mods mod down my previous to 0..

    Here's take 2: the bad template coder's Hello World

    template <char a, char b, char c = 'l', char d = 'o'> void print_hello_world(void)
    {
    printf("%c%c%c%c%c w%cr%cd\n", a, b, c, c, d, d, c);
    }

    int main(void)
    {
    print_hello_world<'h', 'e'>();
    return 0;
    }

  72. Re:Templates are the best C++ feature imho....BUT. by Arandir · · Score: 1

    It's probably something to do with the 'export' keyword.

    Not at all. Very few compilers support that. The problem with VC++ are many, but one of the major ones is that it doesn't support templatized member functions (at least not in VC++ 6).

    --
    A Government Is a Body of People, Usually Notably Ungoverned
  73. Re:Templates are the best C++ feature imho....BUT. by be-fan · · Score: 1

    G++ isn't 100% standards complient, but it's pretty damn good. It compiles almost all of Boost. That's more than can be said of Visual C++ 6 or 7. 7.1 is supposed to be better, but IIRC, it's still in beta.

    --
    A deep unwavering belief is a sure sign you're missing something...
  74. Re:Templates are the best C++ feature imho....BUT. by be-fan · · Score: 1

    Ha ha. Silly MS programmers with their Visual C++ 6.x. Either spend the money and upgrade to 7.0, or be a real man and use GCC.

    --
    A deep unwavering belief is a sure sign you're missing something...
  75. It isn't templates, it's bad programming. by tgv · · Score: 1

    What's extensive? I've got my code built on template classes for lists, sets and associative arrays and the main program is 100k lines. Compile times on an old 500MHz Linux machine with gcc are completely acceptable. Compile times on my even slower mac with CodeWarrior are a little worse, but still acceptable.

    Debugging? Both platforms handle templates transparently. Especially CodeWarrior does a nice job in its totally integrated environment, but gdb ain't bad neither.

    Bloat? Neither. Yes, a list of ints will generate exactly the same code as a list of long ints twice, but this kind of template generates little code, so that's a small price to pay for transparency.

    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.

    That's a good point, but it simply refers to bad design and/or programming. Templates do offer an extra way of complicating code, but it doesn't have to be that way. Multiple inheritance can be a similar drag, but simple inheritance almost never fails in helping write clean code. Are you going to argue that inheritance is therefore bad? Didn't think so.

    No, I think templates are really, really useful, and I like them a lot better than the inheritance mechanism. Just keep the design and programming clean, like everywhere else...

  76. Compile-time matrix multiply in C++. by Animats · · Score: 1
    It's been done. Download the Blitz matrix library for C++ and realize the true power of templates to cloud the mind. By using templates as rewrite rules, fixed-size matrix multiplies can be generated inline at compile time. The concept is general and can be extended to arbitrary matrix operations.

    Now that it's been shown to be possible, it's generally considered to be a bad idea. Since superscalar machines came in, loop unrolling can be a lose. Today, branches in tight loops are cheap or free by the second time around, since the branch predictor knows what happened last time. You get more cache misses with bloated code, too. Loop unrolling isn't the big win it used to be.

    1. Re:Compile-time matrix multiply in C++. by renoX · · Score: 1

      > Since superscalar machines came in, loop unrolling can be a lose.

      Uh? Loop unrolling can be a win especially for superscalar processor where you use the unrolling to fill the execution units.

      Of course loop unrolling can also be a loss if you unroll too much or the loop is too big, because of cache problems as you said.

    2. Re:Compile-time matrix multiply in C++. by Animats · · Score: 1
      If the CPU has register renaming, several iterations of the loop can be running simultaneously.

      When I first heard the head of the Pentium Pro team describe how this works, I felt dizzy. But it's do-able and it's now routine. They had to do that to make x86 go fast. With something like a SPARC that has lots of registers, you can unroll loops and have the compiler spread them out across registers, so that parallelism is possible in the user register space. This made unrolling a big win on some RISC-type architectures. But IA-32 (x86) has so few registers that you'd never get much concurrency if you could only have one operation at a time per register. So a different solution was required.

      Register renaming turned out to be a bigger win than having lots of programmer-visible registers. It allows several iterations of a loop to run simultaneously, as long as they don't block on accesses to the same data. Today, there are a lot more registers internally than the few that the programmer sees. The Pentium Pro/II had about 40 arithmetic registers, as I recall.

      The really hard part in all this is handling exceptions and wierd changes in control flow. On x86 machines, you can store into instructions during execution, and everything works right. Most RISC machines (PowerPC, Alpha, MIPS) don't allow that, but x86 "legacy code" requires it. Think about what has to be done to make that work on a superscalar machine.

      It kills performance, of course. Storing into the next instruction might have been a win in the 1980s, but today, it brings the lookahead to a screeching halt, as most of the work in the CPU is discarded, the state of the execution unit is cleared, and instruction decode starts up again.

  77. No red herring by ucblockhead · · Score: 1
    It's no more a "straight jacket" then "assert" is.

    It's a matter of telling the compiler what you expect so that the compiler can tell you if what you expect is wrong.

    It catches bugs.

    You may be interested to know that there were many C++ container libraries that used "derive from object" and runtime casting long before templates were even part of the language. They've been dumped in favor of template containers precisely because template containers have advantages over them. I've used both, and I've also used both Java and C# containers extensively, and believe me, I'd rather be able to tell the compiler what to expect.

    No, confusion between strings and ints isn't a major source of bugs...but when you've got a lot of different classes and a complex hiearchy it is a different story.

    As for design patterns...I find your comments amusing given that the canonical design pattern book used the ultimate dynamic OO language, Smalltalk, in all its examples.

    --
    The cake is a pie
    1. Re:No red herring by jaoswald · · Score: 1

      This C++ template container approach is preferred *within the context of C++*. If you choose C++, then preferring template containers is a no-brainer, and I agree with Stroustrup that templates are essential, even though they were designed in relatively late in the C++ game. That says nothing about what design choices make sense before you have chosen your language of implementation.

      One of the problems is that C++ design (and to a lesser extent Java design) require you to create these type and class heirarchies in order to be able to get the compiler to allow you to express your program. When inheritance is the only way to explain restrictions and relationships to the compiler, you end up doing a lot of inheritance.

      In more dynamic languages, your class heirarchies can often be a lot less elaborate. You can express type checks that cross inheritance boundaries with ease. In the most difficult cases, in languages like CLOS you can create your own meta-classes that allow you to express things in ways other than inheritance.

  78. Straightjackets by ucblockhead · · Score: 1

    Also note that C++ is flexible enough to do it the java way. For example:

    class Object {};

    class String : public Object {
    public:
    String(string s) :internal(s) {}
    operator string() { return internal; }
    private:
    string internal;
    };

    class Int : publoc Object{
    public:
    Int(int i) :internal(i) {}
    operator int() { return internal; }
    private:
    int internal;
    };

    stack<Object&> MyStack;

    Then you can do it the "Java" way. If you don't feel like typing that code, boost has a library that does the same thing.

    --
    The cake is a pie
    1. Re:Straightjackets by jaoswald · · Score: 1

      If you call that flexible, then sure.

      However, it's much less flexible than most dynamic languages because your Object is not shared with any other class heirarchy. Unless everyone who might need your stack is willing to inherit from your Object, then they can't fit your mold.

    2. Re:Straightjackets by ucblockhead · · Score: 1

      You can just create wrapper classes, ala "boost::any".

      --
      The cake is a pie
  79. doubts by fourletterbc · · Score: 1

    Hey where are templates in Java?
    Are you a "working C++ programmer"?