Click here to Skip to main content
Click here to Skip to main content

Templates in C++ - Pros and Cons

By , 3 Dec 2011
 

Introduction to C++ Templates - Pros and Cons

Once upon a time, I decided to collect and organize all the advantages and drawbacks you may experience when using templates in C++.

Advantages

C++ templates enable you to define a family of functions or classes that can operate on different types of information.

  • Use templates in situations that result in duplication of the same code for multiple types.
    For example, you can use function templates to create a set of functions that apply the same algorithm to different data types.
  • You can also use class templates to develop a set of typesafe classes.
  • Templates are sometimes a better solution than C macros and void pointers,
    and they are especially useful when working with collections (one of the main uses for templates in MFC) and smart pointers (from MSDN).
  • A. Stepanov (the creator of STL) notes that some things that seem trivial using templates (such as equality operator, for example) are very difficult to implement with conventional OO techniques such as inheritance and polymorphism.
  • Because their parameters are known at compile time, template classes are more typesafe, and could be preferred over run-time resolved code structures (such as abstract classes). There are some modern techniques that can dramatically reduce code bloat when using templates. Note that these techniques are very complex either.
  • Often, the main reason to use templates in combination with STL – it can drastically reduce development time.

Disadvantages

  • Historically, some compilers exhibited poor support for templates. So, the use of templates could decrease code portability.
  • Many compilers lack clear instructions when they detect a template definition error. This can increase the effort of developing templates, and has prompted the development of Concepts for possible inclusion in a future C++ standard.
  • Since the compiler generates additional code for each template type, indiscriminate use of templates can lead to code bloat, resulting in larger executables. For example, used in Adobe products "… GIL (Generic Image Library) implements type generators.
    One of these generators generates all image types that are combinations of given sets of color spaces and channels.
    This code defines any image t to be one of 4×3×2×2 = 48 possible image types. It can have any of the four listed color spaces, any of the three listed channel depths, it can be interleaved or planar and its pixels can be adjacent or non-adjacent in memory.
    The above code generates 48 × 48 = 2304 instantiations. Without any special handling, the code bloat will be out of control."
    See Efficient Run-Time Dispatching in Generic Programming with Minimal Code Bloat, 2004.
  • Because a template by its nature exposes its implementation, injudicious use in large systems can lead to longer build times.
  • It can be difficult to debug code that is developed using templates. Since the compiler replaces the templates, it becomes difficult for the debugger to locate the code at runtime.
  • Templates are in the headers, which require a complete rebuild of all project pieces when changes are made.
  • No information hiding. All code is exposed in the header file. No one library can solely contain the code (from Wikipedia).
  • Though STL itself is a collection of template classes, templates are not used to write conventional libraries.
    The libraries of templates are header-only: the library code is included in and compiled with the user's code.
    Though, this makes installation and usage of the libraries relatively easy.

In The C++ Programming Language (3rd Edition), B.Stroustrup presents over 20 factors to take into account when programming templates.
Many of them have to do with ensuring that your code is reliable for all input classes, and maintainable.
B. Stroustrup recognizes these pitfalls:

  • The ease with which unmaintainable "spaghetti code" can be generated
  • Automatically generated source code can become overwhelmingly huge
  • Compile-time processing of templates can be extremely time consuming
  • Debugging is not intuitive for most programmers
  • Context dependencies can be difficult to diagnose and even harder to correct (from comments here)

And here is B. Stroustrup's more recent view on templates usage:

  • Prefer a template over derived classes when run-time efficiency is at a premium
  • Prefer derived classes over a template if adding new variants without recompilation is important
  • Prefer a template over derived classes when no common base can be defined
  • Prefer a template over derived classes when built-in types and structures with compatibility constraints are important

See Joint strike fighter air vehicle C++ coding standards, December 2005.

In sharp contrast to the claim that templates cause code bloat, it so happens that templates can be used to save code space.
C++ compiler is not allowed to generate code for an unused template function. This implies that if a program uses only 3 of a template class’ 7 member functions, only those three functions will occupy space in memory. The equivalent optimization for non-template classes is not common (the standard doesn’t require it) and extremely hard to achieve for virtual functions.

See Abstraction and the C++ machine model, B. Stroustrup, 2004.

References

History

  • 29.10.2011 - Initial submission of article
  • 03.12.2011 - Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sergey Chepurin
Russian Federation Russian Federation
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionNo information hiding.memberShakti Misra15 Nov '11 - 23:15 
Actually you can avoid this.
There are ways to hide your information and still use templates.
There is a "export" key word also coming up in the next C++ version.
QuestionTemplatesmembergeoyar3 Nov '11 - 14:38 
I see templates as one of means to auto generate code. You write instructions for the compiler how to generate the code, and the compiler obeys when it sees your order to generate an instantiation of the template.
More to it, you may force the compiler to do some calculation at compile time (I mean meta-programming.)
It seems that you definitely need templates to write libraries, but not in plain apps.
Recently, works by Andrei Alexandresku changed (or complemented?)the concept and use of the template programming, so it seems (to me, of course) that pro and contra of using templates might be updated a little bit.
geoyar

AnswerRe: TemplatesmemberSergey Chepurin3 Nov '11 - 20:48 
Frankly speaking, it is easier to write code using templates, especially when you don't care about code bloat. You also can delegate a big portion of your responsibility with most of safety related concerns to compiler (isn't that nice?).
I think, everyone has something to add to "pros" or "cons" based on his own experience or opinion.
That is why i even didn't try to make any conclusion. Meaning this is up to you as a programmer to decide what to choose.
GeneralRe: Templatesmembergeoyar4 Nov '11 - 15:11 
I agree on 'pros' and 'contras', but working with templates is not so easy. It is the reason why templates are in 'advanced' chapters of C++ books.
When you are designing a template, you are in parallel designing the classes to be used with the template too (to be precise, the concept of the classes.) And this asks for a lot more of experience and deep thinking. Add to it template template parameters, non-types, default parameters, typedefs - a lot of things. Definitely, it is not for a beginner.
 
Anyway, thanks for reply.
geoyar

GeneralRe: TemplatesmemberSergey Chepurin4 Nov '11 - 20:58 
There is no "easy" part in C++. But we can apply a "simple" analogy to a programming process.
This is like designing and building a house - there are even supposed to be windows.
And coders are like masons, bricklayers. So, this is a simple part or beginner level in your terminology. To design a project of a house is a job of an architect - class designer with code safety in mind, advanced level in programming terminology. This job always was a difficult one. Now, you can build the house from different materials depending on your wallet, talent, time available, etc. That is where templates come handy. They are like panels used to construct a buildings from small to skyscrapers. And of course, there is nothing easy in process of building a skyscraper.
QuestionLong compilation timesmemberLorenzo Gatti2 Nov '11 - 6:45 
Unpleasant compilation times, apart from being justified by pushing computation from run time to compilation time (and consequently optimizing much better) can usually be disposed of through code organization: confinement of heavyweight templates into separate source files that are not recompiled without need can be achieved through simple idioms like PIMPL.
AnswerRe: Long compilation times [modified]memberSergey Chepurin2 Nov '11 - 22:33 
Templates are irreplaceable in computation rich applications and scientific libraries (that was proved by STL and Blitz++). The time C++ committee spent on Concepts for C++11 (and finally removed them) tells that templates are considered a very important part of the language. Now, when processors got to their current limit of power, the parallel computing on multicore platforms and metaprogramming with templates are the techniques experts mostly talk about. But i am afraid that these techniques are so complex that most of us are not ready yet to accept (or understand) them properly. This was one of the reasons i have decided to collect at least some of the commonly known and accepted things about templates in this article. For myself - to organize it somehow, and for the others - if they will need it.

modified 3 Nov '11 - 4:55.

QuestionA couple of comments...member_J0N0_29 Oct '11 - 17:51 
It's useful to think of templates and classes as being orthogonal rather than competing technologies.
 
Code bloat is not necessarily a consequence of template explansion. Templates can also be used to generate extremely terse and efficient code (eg uBLAS and Blitz++). Dimensional analysis and other iterative aspects of algorithms can occur at compile time (hence the loooooong builds).
 
Type safety is a key advantage of generic code, but also a source of many incomprehensible compiler messages. Liberal use of const (a good thing) is often abandoned (a bad thing) in the face of hard to compile generic code.
 
Poor compiler support for templates (eg, incomprehensible messages) is mainly due to the relative immaturity of the technology..
 
You say "Templates are sometimes a better solution than C macros and void pointers".
Assuming the language is C++ and not C, I'd say macros and void pointers are not solutions, they are errors! Big Grin | :-D
 

 

AnswerRe: A couple of comments... [modified]memberSergey Chepurin29 Oct '11 - 23:41 
Thanks for your comment. You are right in almost every word.
But this small collection of pros and cons is not intended for an expert or
a programmer experienced in templates. Rather this can help to the ones who
have to choose a way but unwilling to decide not knowing what to expect.
I know that no matter of what you advise them, professionals tend to do what they know or do well.
And rarely prefer solutions new or less known to them.
Anyway, it is always the best to know what you can expect in advance.
I have to disagree with immaturity of technology, because the story about poor compiler support for templates is more than 10 years old. And everybody got used to those long error messages somehow.
Concerning quote about C macros and void pointers, this is a classical example given to every C programmer to illustrate how templates are better than macros. It was a part of MSDN text on templates.
 
Update:To whom it may concern - I forgot to include in References a very good article Techniques for Scienti c C++ by Todd Veldhuizen (the author of Blitz++ math library). Though written in 2000, it has a good description of templates related advantages and drawbacks (and not only this). Recommended.

modified 30 Oct '11 - 9:14.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 3 Dec 2011
Article Copyright 2011 by Sergey Chepurin
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid