C++ Templates: The Complete Guide
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.
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.
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?
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.
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.
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!
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).
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.
"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.
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
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.
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.
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?
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).
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.
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.
Where can I get the tuple template you speak of?
I'm interested since I regularly work in C++ and Erlang/O'Caml/SML.
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.
Of course they aren't always necessary, but sometimes they are down right handy.
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!!!!
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*
Name one compiler that is 100% C++ standard compliant.
IMHO, is that a book like this needs to exist. Templates are *way* too complicated for something that is supposed to reduce complication.
I rarely see this in template discussions but the thing I love about templates is the ability to do template "closures" for lazy evaluation whereby instead of returning the result of a function, you return an object which represents the application of the function to those arguements. This object then gets cast into the final resultant object.
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
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)
Why bother.
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?
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!
http://www.annexia.org/freeware/cpptemplates/index .msp
libguestfs - tools for accessing and modifying virtual machine disk images
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.
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.
VC8 is said to be quite std's compliant. Coming soon ...
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
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.
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.
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.
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.
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.
//y is now equal to 6
//i and iend are "iterators"
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);
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)
{
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!
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.
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.
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.
You could've hired me.
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).
Nice to see the example using the boost library. That library rocks! The Lambda library stuff is very cool as well.
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!
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.
It's probably something to do with the 'export' keyword. Microsoft's C++ compiler simply does not support it. .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.
The problem is that you cannot have a template definition seperate from its declaration (ie, you can't put the prototype in a
"Dying tickles!" -- Ralph Wiggum
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).
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...
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.
I will probably buy this book.
:) 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.
...
,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 :)
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
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
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."
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"?
... 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
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.
...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.
www.boost.org
The documentation for the tuple library is here
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.
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...
Apparently, the evil one is branching out...
Basically the current bool vector should be depreceated as soon as possible.
Only push ints.
Duh.
Garbage collection is cool; unless you dont'
write garbage code.
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.
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>>::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.
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.
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.
So what the fuck IS the book for, if not to learn about templates?
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.
spoken like a true Microsoft drone.
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!
I've never had any problem with Borland's compilation of templates. Have you given C++Builder a try instead of VC?
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.
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;
}
-
Pointers, References and Values
-
Properly Managing Memory Returned by transcode() in the Xerces XML Library (really about refactoring)
-
Pointers to C++ Member Functions
Thank you for your attention.Request your free CD of my piano music.
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;
}
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
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...
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...
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...
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.
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
Also note that C++ is flexible enough to do it the java way. For example:
:internal(s) {}
:internal(i) {}
class Object {};
class String : public Object {
public:
String(string s)
operator string() { return internal; }
private:
string internal;
};
class Int : publoc Object{
public:
Int(int 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
Hey where are templates in Java?
Are you a "working C++ programmer"?