tags:

views:

1848

answers:

13

Are there any drawbacks to using the STL or templates. Are there any situations for which they are inappropriate.

+13  A: 

First, you should use probably use them if they help you solve your problem. Templates are a very important part of C++ and have been part of the standard for years. STL is very powerful and fast at run time and should be supported on all decent compilers, but of course there are issues.

  • If you have a really old compiler, STL might not be completely supported.
  • The thread-safety of the STL implementation might be work for your application
  • Templates can lead to slower compile-times and possibly larger executable, especially with older compilers.
  • Compilers often produce incomprehensible error messages on code using templates.

just to name a few, but the drawbacks of not using them are likely to be much greater.

David Nehme
you think the error messages for templates are bad, try leaving off the semi-colon at the end of a class header file! ;)
tloach
STLfilt helps a lot regarding the error messages.
Luc Hermitte
Both of those are nothing compared to trying to find a sync error in a multithreaded app ;)
Partial
@Luc: Thanks for the STLfilt advice. I didn't know about this. I just tried it and it looks pretty nice.
+8  A: 

Obvious disadvantages:

  • The syntax can be horrible - some bits of template syntax in C++ are really pushing the limits of sanity, and overlap with other parts of the language (e.g. >>)

  • Lots of people don't understand the STL very well, so you might restrict your audience.

  • Error messages tend to be hideously complicated.

  • The design of the STL collections tends to lead to a lot of copying of objects. The original 'smart pointer' (std::auto_ptr) wasn't suitable for use in most collections. Things have improved in this regard recently (TR1)

Will Dean
C++0x should help improve some of this. The ">>" thing is to be fixed, and concepts are supposed to help produce better error messages.
Fred Larson
A: 

There are a lot of philosophical (at best) arguments for and against C++ templates, but the one that I tend to accept the most is that the mechanism by which they are instantiated at compile time generates a considerable amount of code bloat.

While this isn't typically much of a concern, when you're writing code for an embedded system with very limiting restrictions on binary size it makes a significant impact.

hark
The "code bloat" was a real problem with early compilers that supported templates, but not today.
Nemanja Trifunovic
A: 

In the MSVC implementation, std::string has an overhead of 26 bytes PER STRING, even if the string is empty. If you were doing just char*, it would be 4 bytes per string.

Corey Trager
yea, that's likely the "small string" optimization they do, basically if the string is short enough, they'll use a buffer inside the string object instead of allocating one from the heap.
Evan Teran
It's not necessarily a bad thing. The small string optimization can have a huge impact on performance because it reduce considerably the number of memory allocations. One of my programs is incredibly faster with MSVC than gcc because of this. –
Rexxar
A: 

One might be that they translate poorly to other object-oriented languages that don't support templates such as C# and Java, so if you have a developer group coming from those languages, they will face a steeper learning curve.

JohnMcG
+5  A: 

There are several potential benefits and drawbacks

  • Templates expand the size of the resulting code.
  • Templated code is expanded and processed at compile time which may make compile times longer. (On the other hand, executable code may be more efficient).
  • Mis-used STL elements can result in slower code
  • The STL actually makes code more readable (my opinion differs from Will's). Like any language or library, you have to understand it to use it appropriately... which is a drawback for people who don't know it.
  • If you are using templates in a meta-programming sense (don't confuse w/ using the STL), the code looks like a language completely different from C++. It can be harder to parse through what the code is actually doing. (OTOH, done right - meta-programming makes you focus on architecture and design; it also brings more of the errors to compile time vs. runtime. This is a big win when you have a critical feature and you can catch an incorrectly coded piece at compile time rather than having a customer catch it during operation!)

Having said that, we use C++ and templates (and in some areas, meta-programming techniques) to the benefit of our overall code base. The code is slightly larger than it might be without templates, but the trade-offs in performance and maintainability outweigh the size. We do have skilled/experienced C++ programmers working on developing and maintaining the code.

If you're using drawbacks to decide whether to use C++ features/libraries or not - make sure you equally weigh the benefits both for the language and what your project/product/company is willing to trade off. Hope this helps.

Edit: One other major drawback I forgot to mention - portability. If you need to write portable code, templates may not be the right way to go. Most popular compilers today support the STL, however most is not all. The meta-programming techniques can be real killers to portability, so that is a definite consideration for deciding appropriateness of its use.

twokats
A: 

The way templates get instantiated requires you to be careful about how to declare and define your templates when you share them across translation units. The book "C++ templates: The complete guide" is a good source of information about how to handle this.

Compiler and linker error messages for templates tend to be very, very verbose. You'll have to get used to that, and I think there are some scripts/tools that make them more readable, but I don't have any experience with them.

But apart from that templates are great!

andreas buykx
I find it offensive that you compare templates to macros.
Templates are not somewhere between macros and compiled code. Templates *are* compiled code. They do not subvert the C++ type system like macros do, and they are 1-st class constructs which are compiled by the compiler -- not by the preprocessor.
John Dibling
I agree, templates are compiled code, and I agree, templates are everything that macros are not. My (admittedly ill phrased) point was that template instantiation adds a complication in organizing the code. I think BTW that the book had a similar statement about code, macros and templates.
andreas buykx
I quote from "C++ Templates" (ch. 6) : "Templates are a little different from ordinary code. In some ways templates lie somewhere between macros and ordinary (nontemplate) declarations."
andreas buykx
+3  A: 

For embedded device programming (in my case -- smartphones). Templates are discouraged because of the concern for generated code size (small amount of RAM and disk space). Also the compilers are pretty ancient and probably can't handle some template related constructs.

Kasprzol
+1  A: 

Complex STL containers (and for that matter any complex C++ class) make debugging much more difficult.

Besides the unreadable error messages mentioned before, there is usually very little support in current debuggers for handling STL constructs. For example, it is much easier to examine a native C array at runtime, than a vector<> container.

Hopefully the situation will change with time. Other than that, templates are wonderful.

nimrodm
+2  A: 

To paraphrase Andrei Alexandrescu of Modern C++ Design fame. Template are an orthogonal structure to multiple inheritance. They both have complementary trade-offs and benefits. Templates have rich mechanics but specialization of templates does not scale.

A: 

See the templates section of the C++ FQA [sic] for lots of good reasons to not use templates.

Adam Rosenfield
The FQA is full of FUD and should be taken as such.
ididak
+1  A: 
  1. Heavy template abuse (in particular template meta-programming and Boost addiction) can lead to excessively long compile and link times.

  2. You also wind up with executables that have considerably larger (unstripped) binaries, but generally that isn't a terrible issue.

  3. Poorly designed templates can also increase code duplication further exacerbating the executable size issue.

  4. For class templates with large implementations also need to consider the fact that using a template for them means moving the entire class body into a header somewhere. This places a lot more load on the linker if the template is used in multiple places.

  5. Error messages from heavily templated code can be daunting to the uninitiated and are rarely if ever as clear as the error messages you get from untemplated code.

That said, for most applications templates are a wonderful tool for code reuse and help lift the level of discourse from reimplementing to reusing code; rarely do these issues trump the benefits.

Edward Kmett
A: 

The goal of template is to provide abstraction with minimal performance penalty. In most cases, benefits outweigh drawbacks. Most of the issues with templates are from compiler and debugger support.

My pet peeve about template: it defeats smart build system due to header dependencies. Developing template code tends to cause a lot more recompilation of untouched code than developing a pure OO based system, especially if the latter use the DIP (dependency inversion principle) well. This exacerbates the slow compilation problem. OTOH, faster dev hardware these days make things much more tolerable than before.

As for STL (as well as Boost), their goal is to provide portable and reasonably efficient data structure and algorithms. They're not necessary the best choice for certain performance critical applications. For example: although hash_map (tr1/unordered_map) performs reasonably well for average cases, special purpose hash tables (e.g., the google sparse/dense hash table library) can greatly outperform generic STL implementations in terms of memory usage or speed.

ididak