This post originated from an RSS feed registered with Java Buzz
by noe casas.
Original Post: Generic programming in C++: general stuff
Feed Title: SoftwareDesignStuff
Feed URL: http://feeds2.feedburner.com/softwaredesignstuff
Feed Description: This blog is a place to share my ideas and opinions on topics like software design, good/bad programming practices, design patterns, programming languages, frameworks, software technology and so on, and to discuss them with you.
Much has been said about C++ generic programming, some things good, some things not. In this post, which is the first in a series devoted to C++ generic programming, I would like to dig in the role templates play in the C++ programmer toolset.
C++ is a multi-paradigm language, supporting procedural, object oriented and generic programming, but most of the C++ projects I have ever seen use basically OOP, plus a bit of generic programming just enough to deal with STL and/or BOOST or to implement not more than containers of T 1.
I see a big gap between C++ hardcode practitioners and the average C++ programmer concerning templates. While most C++ programmers can use runtime polymorphism with no problem, they are hardly able to code a simple container-of-T by themselves. On the other hand, C++ experts tend to evangelize the goods of template metaprogramming. Why is generic programming such an infrequent tool in the daily coding? What do C++ gurus see in the use of templates that other people "miss"?
The main problems why -in my opinion- templates tend not to be used are:
Lack of knowledge on the templates mechanism and on its syntax, related to the fact that most mainstream languages do not have the capabilities for generic programming C++ does.
Inherent difficulty to get it right with templates: as everybody knows, errors in code that uses templates can be a nightmare to decypher, and the more you dig into generic programming idioms, the longer the error messages you get.
They break encapsulation: templatized code imposes implicit (sorry, no concepts in C++0x) constraints on the template parameters (e.g. if the templatized code uses the template parameter's copy constructor, every instantiation will require such constructor from the parameter) Thus code that uses the template, has to know its implementation to properly use it. Failure to provide template parameters that match those implicit expectations is the most frequent source of errors in code using templates.
In the following posts, I will try to explore the very basic template syntax, template specialization common uses, usual generic programming idioms, and some metaprogramming spells...
1. The best test I came up with to challenge my opinion is to google code search the key terms for polymorphism and generic programming in C++... search: "template <" lang:c++ --> 339000 search: "virtual " lang:c++ --> 2130000 results If anybody thinks there is a better way to measure it, comment please!