Click here to Skip to main content
15,886,787 members
Articles / Programming Languages / C++

Templates in C++ - Pros and Cons

Rate me:
Please Sign up or sign in to vote.
4.68/5 (17 votes)
3 Dec 2011CPOL5 min read 88.3K   30   18
Advantages and drawbacks of using templates in C++ projects

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)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGreat Article Pin
Saurabh Nissa20-Feb-20 4:16
professionalSaurabh Nissa20-Feb-20 4:16 
QuestionTemplates are of the devil Pin
bearvarine5-May-15 10:51
bearvarine5-May-15 10:51 
I've been using C++ since the early '90s. It is a lovely language and I've appreciated having my cake (in the form of all low-level C features being available) and eating it too (The wonderful STL and Boost libraries to reduce coding time). That having been said, I see templates as at best -- providing a mixed blessing of type flexibility with a relatively simple syntax, but at worst creating a nearly undecipherable alphabet soup of functional linkages and extensions when used in practice.

Originally, the idea behind templates seemed focused on building flexible container objects. A worthy endeavor, giving us such gems as the STL library. But then, as with any kind of new hammer, people began to experiment with what all new kind of nails could be pounded down with it. Quickly we began to be confronted with code objects defined with multiple templates sometimes nested, with usage patterns that were no longer easily understandable from the code alone. Code with template-heavy abstractions began to resemble APL, a symbolic language renowned for its inscrutability and adds difficulty to a software maintenance programmer's job of understanding legacy code for repair and improvement.

The core problem as I see it, is that software development has evolved expectations beyond what C++ can comfortably handle with its current design. Scripting languages such as Perl, Python, Ruby, and JavaScript are not as strongly typed as C++ and can easily handle tasks which require generic types without adding to the complexity of the syntax notation, thus simplifying maintenance by perhaps an order of magnitude. Because of this, the cost of coding in C++, C#, and java -- feature for feature -- will continue to exceed the cost in other languages with simpler ways of handling generic types.

Thus in the end, the extra burden of complexity levied by heavy use of templates may over time cause individuals and organizations to rethink their language choice and move away from C++ as the language of choice for their next projects. As time goes on it is just too costly maintain millions of lines of inscrutable, arcane code when other reasonable alternatives are available.

Thus, in the long run, templates may very well destroy the very language they deign to improve. One might call them a modern day poster-child of a Faustian Bargain.
AnswerRe: Templates are of the devil Pin
Sergey Chepurin10-Jun-15 9:29
Sergey Chepurin10-Jun-15 9:29 
GeneralMy vote of 5 - Very important article Pin
Michael Haephrati13-Jul-14 6:59
professionalMichael Haephrati13-Jul-14 6:59 
QuestionNice Pin
Manikandan106-Jun-14 20:38
professionalManikandan106-Jun-14 20:38 
QuestionNo information hiding. Pin
BrainlessLabs.com15-Nov-11 23:15
BrainlessLabs.com15-Nov-11 23:15 
AnswerRe: No information hiding. Pin
steveb17-Aug-13 4:12
mvesteveb17-Aug-13 4:12 
AnswerMessage Closed Pin
3-Sep-13 1:12
Member 102203673-Sep-13 1:12 
QuestionTemplates Pin
geoyar3-Nov-11 14:38
professionalgeoyar3-Nov-11 14:38 
AnswerRe: Templates Pin
Sergey Chepurin3-Nov-11 20:48
Sergey Chepurin3-Nov-11 20:48 
GeneralRe: Templates Pin
geoyar4-Nov-11 15:11
professionalgeoyar4-Nov-11 15:11 
GeneralRe: Templates Pin
Sergey Chepurin4-Nov-11 20:58
Sergey Chepurin4-Nov-11 20:58 
QuestionLong compilation times Pin
Lorenzo Gatti2-Nov-11 6:45
Lorenzo Gatti2-Nov-11 6:45 
AnswerRe: Long compilation times Pin
Sergey Chepurin2-Nov-11 22:33
Sergey Chepurin2-Nov-11 22:33 
QuestionA couple of comments... Pin
_J0N0_29-Oct-11 17:51
_J0N0_29-Oct-11 17:51 
AnswerRe: A couple of comments... Pin
Sergey Chepurin29-Oct-11 23:41
Sergey Chepurin29-Oct-11 23:41 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.