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
andfor_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)
- STL and the algorithms (what’s the difference between
- 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:
- C++ Templates: The Complete Guide by David Vandevoorde and Nicolai Josuttis (thorough introduction to the subject of templates)
- Modern C++ Design. Generic Programming and Design Patterns Applied by Andrei Alexandrescu (what is the less known way of using templates to simplify your code, make development easier and result in code robust to changes)
- C++ Template Metaprogramming by David Abrahms and Aleksey Gutov (again – different way of using the templates)
- More C++ Idioms from Wikibooks presents some nice ideas.