






C++ Templates: The Complete Guide 450
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.
Low level details and issues? (Score:3, Funny)
Re:Low level details and issues? (Score:4, Funny)
Memory management works????
Re:Low level details and issues? (Score:3, Interesting)
In fact, memory mangement is one of the wonderful things about Java (and other languages with good garbage collection), something that makes me shudder to think about going back to C/C++. I can't remember ever thinking, "oh, even though I'm no longer using this memory allocation I'd like to keep it around a little longer." With the one except
Bloat (Score:2, Insightful)
The seemed to me a recipe for bloat/cache thrashing/ugliness. I did not see bloat addressed in the review. In my reactionary way I continue to believe my prejudices.
Does anyone who has u
Re:Bloat (Score:5, Insightful)
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
So, no, templates don't necessarily lead to bloating/ugliness/slowdowns/whatever if done properly.
Re:Bloat (Score:4, Interesting)
That is my biggest complaint with templates. Compilation errors can be horrendous, especially as they often appear far from point where you've made the error. My second biggest complaint are the debugger symbols that get produced for templates.
Re:Bloat (Score:4, Insightful)
Re:Bloat (Score:4, Insightful)
Some people say they use the good ole void* instead of a template. Those people sometimes do memory debugging for months.
Only when misused (Score:2, Insightful)
No bloat if you design correctly. (Score:5, Insightful)
Re:Bloat (Score:3, Interesting)
The STL, especially, makes C++ an order of magnitude more usable and powerful.
Re:Bloat (Score:4, Redundant)
No, templates are often anti-bloat. With a good optimizing compiler, a dizzying heirarchy of layers of abstraction can often compile down to 2 or 3 machine opcodes. If you understand how to use STL properly (which includes double-checking your results by disassembling critical points in the binary and inspecting them) you can often get code that is almost as fast as hand-coded assembly. I think that in general, if you use the other main approach to abstraction in C++ (virtual method calls), it's harder for the compiler to crush all of the layers of abstraction down to zero.
The main problem with C++ templates IMO is that they feel "brittle". It's hard to create large modular programs because of C++ #include dependencies and binary interface difficulties. I think that the best approach for large programs is to identify the performance-critical pieces and code them up in C++/STL as native modules for a nice high-level language like Python, then use the high-level language to glue everything together.
Re:Bloat (Score:5, Informative)
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 [cuj.com].
Continue to believe your prejudices if you want, but consider that if you can't use or write templates you've essentially shut yourself out of a huge segment of the C++ development job market. I would certainly never hire a "C++ developer" that don't at the very least have thorough experience with the STL, and preferrably understand how to write (and when to write) templates.
Re:Bloat (Score:3, Insightful)
...
I would certainly never hire a "C++ developer" that don't at the very least have thorough experience with the STL, and preferrably understand how to write (and when to write) templates
As it happens most of my work is done down near the hardware. So those peksy issues of the relationship of compiled code to the hardware - which cut directly across things like having 24 copies of each method in a class because the class is
Re:Bloat (Score:5, Interesting)
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.
Re:Bloat (Score:2)
-m
Re:Bloat (Score:2)
Not when used properly. It should be mentioned, however, that early implementations in a number of compilers tended to create object code for identical template instances in multiple places (basically treating templates like your "super #define"). This really did_ lead to a great deal of bloat.
Modern compilers (at least the ones I use) instantiate templates more intelligently. The only real problem I've seen is that templates, like a lot of u
Re:Bloat (Score:2)
You have an excellent point. There's a subset of C++ called Embedded C++ [caravan.net] that removes templates, multiple inheritance, new-style casts, exceptions, and some other features. Those are features that tend to make C++ programs bigger and slower than C programs. By limiting the features used by a program and its libraries, and Embedded C++ compiler is able to make leaner, faster code. This can be a huge benefit in embedded systems, hence the name.
Re:Bloat (Score:3, Insightful)
If you don't use multiple inheritance, then you don't suffer a performance drop. If you don't use exceptions, you don't suffer a performance drop. Templates, namespaces, and new-style c
Re:Bloat (Score:2)
On the other hand, each specialization could be fast and memory-efficient because the compiler knows the size of the objects being stored - none of this putting integers into and out of boxes at run time whenever you want to store them in a container, as happens in Java and in many implementations of more high-level langua
Re:Bloat (Score:3, Informative)
Re:Bloat (Score:2)
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
Re:Bloat: O.K., I'll bite (Score:5, Informative)
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<T>(T *arg1, T *arg2). (You could, alternately still pass that function to the generic sort routine, if you had different comparison functions for the same types of data (say, case-sensitive and case-insensitive sorting, or lexicographic vs. ASCII text sorting, etc.).)
Note the inline declaration. This lets a smart compiler code the call to the generic function inline, avoiding a double function call. In practice, if the only thing you are doing is some type casting, no additional code is generated.
So, you still have the potentially dangerous downcasting, but you've encapsulated it inside a template definition, relieving the application programmer to have to worry about it. Does all this mean extra work? It sure looks that you have to come up with a generic implementation and then make a nice and pretty templated type-safe wrapper around it.
This is true, and well worth the effort for code that has to be robust and easy to use, particularly by others. Library writers know this rule all too well.
Of course, in a pinch, or when a generic implementation is not obvious, or known to be non-existent, or when a particulary implementation exists for some types of objects, you can punt and let the compiler generate multiple instances of type-safe code, without a generic back-end implementation, accepting the code bloat that results.
In the end, it becomes a matter of compromise and wise design decisions. Unfortunately, with choice, comes the effort to chose, and to chose wisely. It is the unwise use of templates that leads to their sometimes ill-deserved "code bloat" reputation. One of the differences between the skilled and less-skilled programmer is the ability to make these choices correctly and quickly, leveraging the language features that let the corresponding design decisions be put into practice.
Other related C++ topics would include the notions that "multiple inheritence leads to slow code," "exception handling and run-time type information have high overhead". Again, one has to weigh the advantages offered by these techinques against the skill needed to use them wisely, and the performance penalty paid. I'll let someone else chime in now.
Re:Bloat (Score:3, Informative)
Though personally, I find little bloat to speak of. It has been literally a decade since I had to worry about memory size. (As opposed to worrying about speed literally yesterday.)
The largest C++ project I'm working on write now is about 7,000 lines of code. It makes heavy use of both the STL and templates. It runs about 500k on disk and seems to take between one and t
Re:Bloat (Score:3, Interesting)
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 ha
Genetic programming (Score:3, Funny)
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
Professional Computing Series (Score:2, Informative)
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.
What about Java/C++ developers (Score:3, Interesting)
My J-Developer friend was just telling me the other day how he longed for templates in Java.
Re:What about Java/C++ developers (Score:2)
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.
Re:What about Java/C++ developers (Score:2)
Not for me... (Score:4, Funny)
An 800 page book written by true professionals"
Re:Not for me... (Score:2)
What makes the haxx0r3d and o\/\/n3d MS servers is that at one time Billy G. said one of the advantage of Windows over UNIX was that UNIX kept on having buffer overflows, and look at this Microsoft stuff thats so much better. This is back in some sendmail bug days, and before Windows was really a net target. Anyone else remember Trumpet Winsock?
The one thing that scares me really is not the hacks we know about, but the ones we don't. Fuck Cod
C++ is a systems language??? (Score:2, Troll)
The C++ programming language is widely regarded as a good systems programming language
This alone makes the review suspect. It is a shame that anyone believe this. All I have seen from C/C++ is bloat at runtime and speed issues because programmers do not understand the under lying "cost" of the any function they call and too many functions (and sub-languages like fprint) to call.
Re:C++ is a systems language??? (Score:2)
Re:C++ is a systems language??? (Score:2, Informative)
However, don't automatically assume that C++ is always slower than C. Sometimes the opposite is true because you can do some stuff at compile-time in C++ that C would normally do at run-time.
The often quoted example is the sort routine in the C++ library verses qsort(?) in the standard C library. Both library calls take a comparison function as a parameter. However, because the C++ versio
Re:C++ is a systems language??? (Score:2)
Be that as it may be, there are many invaluable lessons in that book. I would recommend "C++ Templates" from Vandevoorde and Josuttis before you even attempt Alexandrescu's book.
Re:C++ is a systems language??? (Score:2)
Re:C++ is a systems language??? (Score:2)
Re:C++ is a systems language??? (Score:2)
I often find the opposite to be true. Real speedup can often be found in improving key algorithms used by a program. And that is often easier to do with proper abstraction. With good abstraction it could be possible to replace a linked list implementation with hash implementation, for example, without having to touch boatloads of code. It's much harder to do if you've got a big ball of mud that doesn't use a
Templates are the best C++ feature imho....BUT... (Score:4, Interesting)
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!
Re:Templates are the best C++ feature imho....BUT. (Score:2, Interesting)
Re:Templates are the best C++ feature imho....BUT. (Score:2, Informative)
Templates and Linked Lists.. (Score:2, Interesting)
One other point (Score:4, Funny)
No portability info? Bummer. (Score:5, Insightful)
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.
An excellent book, but be aware (Score:5, Informative)
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 [moderncppdesign.com] 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 problem with C++... (Score:3, Interesting)
Closures with tamplates (Score:2, Interesting)
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 y
What I want explained to me... (Score:2)
Re:What I want explained to me... (Score:2)
You can get round this by putting the entire template definition in the header file, which may lead to massive code bloat if your linker doesn't combine all the multiple definiti
Re:What I want explained to me... (Score:2, Insightful)
You can get round this by putting the entire template definition in the header file, which may lead to massive code bloat if your linker doesn't combine all the multiple definitions.
That is essentially #include "Foo.cpp", which is insanely ugly. Come to think of it, it's been so long since I last tried to use that I cannot remember exactly what I was trying to do with it -- except that it would have made things a lot easier.
As far as I can recall (without getting into specifics), I had a limi
Re: Put templated code in the .h file (Score:2)
It's a real shame if this book doesn't explain implementation details like this!
Re:What I want explained to me... (Score:4, Insightful)
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).
Extensive template use is dangerous (Score:5, Insightful)
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!
C++ templates - not just powerful, Turing complete (Score:2)
Spirit - a lex/yacc written in C++ templates (Score:3, Informative)
struct calculator : public grammar<calculator> {
template <typename ScannerT>
struct definition {
definition(calculator const& self) {
expression = term
>> *( ('+' >> term)[&do_add]
| ('-' >> term)[&do_subt]
);
term = factor
Templates are a crutch (Score:5, Interesting)
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.
C++ Template Strength (Score:2, Interesting)
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
Standard C++ with STL is the best abstract machine (Score:3, Interesting)
This review isn't very good (Score:3, Interesting)
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.
Re:Are templates always necessary? (Score:5, Insightful)
Re:Are templates always necessary? (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].
Re:Are templates always necessary? (Score:3, Informative)
Re:Are templates always necessary? (Score:2, Informative)
Re:Are templates always necessary? (Score:2)
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.
Re:Are templates always necessary? (Score:2)
See this:
http://jcp.org/en/jsr/detail?id=014 [jcp.org]
Re:Are templates always necessary? (Score:2)
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.
Re:Are templates always necessary? (Score:2)
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 d
Re:Are templates always necessary? (Score:4, Informative)
http://www.cis.unisa.edu.au/~pizza/gj/ [unisa.edu.au]
Re:Are templates always necessary? (Score:4, Informative)
Re:Are templates always necessary? (Score:5, Insightful)
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.
Re:Are templates always necessary? (Score:5, Funny)
WHO ARE YOU AND WHAT HAVE YOU DONE WITH SLASHDOT!?
Re:Are templates always necessary? (Score:4, Informative)
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).
Re:Are templates always necessary? (Score:2, Interesting)
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 th
Re:Are templates always necessary? (Score:3, Interesting)
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).
Re:Are templates always necessary? (Score:2)
(just kidding)
Re:Are templates always necessary? (Score:4, Interesting)
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.
Re:Are templates always necessary? (Score:4, Informative)
if (x instanceof Number) {
Number n = (Number) x;
}
Now time how much slower it is...
Re:Are templates always necessary? (Score:4, Insightful)
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.
Re:Are templates always necessary? (Score:4, Interesting)
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!
Re:Are templates always necessary? (Score:3, Insightful)
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
Re:Are templates always necessary? (Score:2)
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.
Re:Are templates always necessary? (Score:5, Informative)
Re:Are templates always necessary? (Score:3, Interesting)
Java is supposed to have templates from 1.5 anyway IIRC, so you'll have a choice then.
Re:Are templates always necessary? (Score:5, Informative)
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:
gets boring really quickly. Templates in collections saves you all that downcasting.In fact, it's so useful, it's appearing in Java [sun.com] in JDK1.5, courtesy of JSR 14 [jcp.org].
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.
Re:Are templates always necessary? (Score:3, Informative)
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 [rpi.edu].
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 polymorphis
Re:Are templates always necessary? (Score:5, Insightful)
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 [stlport.org] 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.
3D Math (Score:2, Interesting)
There is an interesting use for templates in 3D vector math:
http://www.flipcode.com/tutorials/tut_fastmath.sht ml [flipcode.com].
It's a kludge, but it provides some real performance benefits.
Re:3D Math (Score:3, Insightful)
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
Re:Are templates always necessary? (Score:2)
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
Re:Are templates always necessary? (Score:2)
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 container
Re:Are templates always necessary? (Score:4, Insightful)
Read the book "Modern C++ Design" and find a whole new set of uses for templates.
Of course, a lot of this you also get from things like Lisp's defmacro and eval-when commands, but few modern languages have these abilities.
Re:Are templates always necessary? (Score:3, Informative)
And there's nothing evil about templates. They are merely functions parameterized by classes except maybe some aspects of their implementation in C++. They have a perfectly respectable history in computer science. Check
Re:Are templates always necessary? (Score:3, Informative)
Check out the boost libraries, [boost.org] Alexandrescu's "Modern C++ Designs" and The Database Template Library [freshmeat.net] for more spiffy things you can do with templates.
Re:Jesus christ (Score:2, Insightful)
Re:Jesus christ (Score:3, Insightful)
Adobe Suits: What's the timeframe on the next Photoshop rev?
AC: Well, given that we're rewriting it in Python, I'd say you better be prepared to wait.
Adobe Suits: Jesus christ.
There is so much investment in C++ in the desktop application development space, that you better get used to hearing about C++ for years and years to come.
Re:template versus derivation (Score:2, Informative)
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 << 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 inst
Re:template versus derivation (Score:2)
Re:template versus derivation (Score:3, Informative)
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 problem
Re:and? (Score:2)