tags:

views:

1054

answers:

9

Hey,

I've been talking with friends and some completely agree that templates in C++ should be used, others disagree entirely.

Some of the good things are:

  • They are more safe to use (type safety).
  • They are a good way of doing generalizations for APIs.

What other good things can you tell me about C++ templates?

What bad things can you tell me about C++ templates?

Edit: One of the reasons I'm asking this is that I am studying for an exam and at the moment I am covering the topic of C++ templates. So I am trying to understand a bit more on them.

+3  A: 

I don't see how they are hard to read. What is unreadable about

vector <string> names;

for example? What would you replace it with?

anon
I mean the template source code, I'll correct it on the question
fmsf
vector<string>? Did you mean vector<basic_string<char, char_traits<char>, allocator<char> >, allocator<basic_string<char, char_traits<char>, allocator<char> > > >?
Thomas
@Thomas, what's wrong with that?
greyfade
@greyfade: If you enjoy working with types like that, I've got a few pages of template compiler error messages here that you'd just *love*.
j_random_hacker
@Thomas, @j_random_hackerGive us the alternative (generic, versatile, robust) then.As for reading the errors, after some time you can get quite skilled with it and filter crap instantaneously. One day of Spirit or Phoenix and +10 in error reading skill ;)
Anonymous
STLfilt is our friend: it simplifies the error messages to keep only what is relevant.
Luc Hermitte
@Thomas.typedef basic_string<char, char_traits<char>, allocator<char> >, allocator<basic_string<char, char_traits<char>, allocator<char> > > string;'nuff said.
Ed Woodcock
@Ed: And yet,it's no different in terms of structure than a simple function call. You have the class template, followed by the template arguments. Replace angle brackets with parens, and it should look very familiar. It's verbose, yes, but that's because it's customizable, not because of templates.
jalf
+1  A: 

There is nothing inherently good or evil about templates. They are merely a tool, and there is a time and a place for their use. I tend to fall on the "don't use templates" side simply because I've seen it done badly so often. I loath the STL because it is impossible to debug and does all sorts of memory allocation under the covers that many developers do not fully understand leading to all sorts of performance bugs.

That said, templates are fine as long as they're doing something simple. They're fine as long as it is obvious from the function declaration what it is they are doing.

Templated classes are fine too, but–and this is my rule–they should not allocate memory. Callers should allocate, e.g. nodes, and then hand them to the templated class. Same for destruction.

jeffamaphone
can you explain why template classes should not allocate memory? are you trying to get the strong exception guarantee for all your code?
Its not a rule, just a guideline that I like to live by. I don't like it when callers don't realize they're allocating a ton of memory, and most template libraries don't go out of their way to make it obvious. I also think its better for callers to manage lifetime. At least for native code.
jeffamaphone
+1  A: 

Templates should be used sparingly.

"Awful to debug" and "hard to read" aren't great arguments against good template uses with good abstractions.

Better negative arguments would go towards the fact that the STL has a lot of "gotchas", and using templates for purposes the STL already covers is reinventing the wheel. Templates also increase link time, which can be a concern for some projects, and have a lot of idiosyncrasies in their syntax that can be arcane to people.

But the positives with generic code reuse, type traits, reflection, smart pointers, and even metaprograms often outweigh the negatives. The thing you have to be sure of is that templates are always used carefully and sparingly. They're not the best solution in every case, and often not even the second or third best solution.

You need people with enough experience writing them that they can avoid all the pitfalls and have a good radar for when the templates will complicate things more than helping.

Dan Olson
+24  A: 

Templates are a very powerful mechanism which can simplify many things. However to use them properly requires much time and experience - in order to decide when their usage is appropriate.

For me the most important advantages are:

  • reducing the repetition of code (generic containers, algorithms)
  • reducing the repetition of code advanced (MPL and Fusion)
  • static polymorphism (=performance) and other compile time calculations
  • policy based design (flexibility, reusability, easier changes, etc)
  • increasing safety at no cost (i.e. dimension analysis via Boost Units, static assertions, concept checks)
  • functional programming (Phoenix), lazy evaluation, expression templates (we can create Domain-specific embedded languages in C++, we have great Proto library, we have Blitz++)
  • other less spectacular tools and tricks used in everyday life:
    • STL and the algorithms (what's the difference between for and for_each)
    • bind, lambda (or Phoenix) ( write clearer code, simplify things)
    • Boost Function (makes writing callbacks easier)
    • tuples (how to genericly hash a tuple? Use Fusion for example...)
    • TBB (parallel_for and other STL like algorithms and containers)
  • Can you imagine C++ without templates? Yes I can, in the early times you couldn't use them because of compiler limitations.
  • Would you write in C++ without templates? No, as I would lose many of the advantages mentioned above.

Downsides:

  • Compilation time (for example throw in Sprit, Phoenix, MPL and some Fusion and you can go for a coffee)
  • People who can use and understand templates are not that common (and these people are useful)
  • People who think that they can use and understand templates are quite common (and these people are dangerous, as they can make a hell out of your code. However most of them after some education/mentoring will join the group mentioned in the previous point)
  • template export support (lack of)
  • error messages could be less cryptic (after some learning you can find what you need, but still...)

I highly recommend the following books:

Anonymous
Ty this is nice :)
fmsf
+8  A: 

On the positive side, C++ templates:

  • Allow for generalization of type

  • Decrease the amount of redundant code you need to type

  • Help to build type-safe code

  • Are evaluated at compile-time

  • Can increase performance (as an alternative to polymorphism)

  • Help to build very powerful libraries

On the negative side:

  • Can get complicated quickly if one isn't careful

  • Most compilers give cryptic error messages

  • It can be difficult to use/debug highly templated code

  • Have at least one syntactic quirk ( the >> operator can interfere with templates)

  • Help make C++ very difficult to parse

All in all, careful consideration should be used as to when to use templates.

Colin
A: 

Advantage: Generic Datatypes can be created.

Disadvantage: Code Bloating

Vinay
+0. IMHO, of all the disadvantages, code bloating is about the least significant.
j_random_hacker
Code Bloat is not a problem. Because it is the code you would have had to write anyway.
Martin York
@Martin: Exactly!
j_random_hacker
+1  A: 

One of the disadvantages I haven't seen mentioned yet is the subtle semantic differences between regular classes and instantiations of class templates. I can think of:

  1. typedefed typenames in ancestor types aren't inherited by template classes.
  2. The need to sprinkle typename and template keywords in appropriate places.
  3. Member function templates cannot be virtual.

These things can usually be overcome, but they're a pain.

j_random_hacker
+2  A: 

Good points: powerful; allows you to:

  • prescribe compile-time attributes and computation
  • describe generic algorithms and datastructures
  • do many other things that would otherwise be repetitive, boring, and mistake-prone
  • does them in-language, without macros (which can be far more hazardous and obscure!)

Bad points: powerful; allows you to:

  • provoke compile-time errors that are verbose, misleading, and obscure (though not as obscure and misleading as macros...)
  • create obscure and hazardous misdesigns (though not as readily as macros...)
  • cause code bloat if you're not careful (just like macros!)

Templates vastly increase the viable design space, which is not necessarily a bad thing, but it does make them that much harder to use well. Template code needs maintainters who understand not just the language features, but the design consequences of the language features; practically speaking, this means many developer groups avoid all but the simplest and most institutionalized applications of C++ templates.

In general, templates make the language much more complicated (and difficult to implement correctly!). Templates were not intentionally designed to be Turing-complete, but they are anyway -- thus, even though they can do just about anything, using them may turn out to be more trouble than it's worth.

A: 

Reusable code is made with template. Its application is in accordance with the profile of each.

lsalamon