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!