Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

An Introduction To C++Templates


Published on

Published in: Technology, Education
  • Be the first to comment

An Introduction To C++Templates

  1. 1. An Introduction to C++ Templates Why Templates? Generic programming has become a dominant programming paradigm in C++, particularly after the incorporation of the Standard Template Library (STL) as part of the standard library in 1996. Templates - the language feature that supports generic programming in C++ - was originally conceived for supporting ‘parameterized types’ (classes parametrized by type information) in writing container classes. Templates are a compile time mechanism. Because of this, there is no runtime overhead associated with using them. Also, using templates is completely type safe. Templates help to seamlessly integrate all types and thereby let programmers write code for one (generic) type. So, it serves as a mechanism for writing high-level reusable code, which is known as ‘generic programming’. Like the structured, modular and object oriented programming approaches, generic programming is another programming approach (and C++ supports all these four programming paradigms! For this reason, C++ is referred to as a ‘multi-paradigm’ language). Writing Reusable Code Two primary means of providing reusable functionality in conventional object-oriented systems is through inheritance and composition. Inheritance refers to creating subclasses or subtypes from existing classes and composition refers to providing objects of other class types as data members. quot;Parameterized types give us a third way (in addition to class inheritance and object composition) to compose behavior in object-oriented systems. Many designs can be implemented using any of these three techniquesquot;, observes [Gamma et al, 1994]. Templates look at the problem of reusability in a different way - it uses type independence as the basis rather than inheritance, polymorphism and composition. One of the main objectives of C++ is to support writing low-level code for systems programming in which performance is an important consideration. C++ templates do not add any additional performance overheads and still promises high level of reusability; hence, templates have become very important in C++ for writing reusable code. Use of Templates The (re)use of tested and quality template code can save us from lots of programming effort and can be helpful in variety of programming tasks. The three important advantages of using templates are: • type safety (as strict type checking is done at compile time itself), • reusability (as writing code for one generic type is enough) and • performance (as templates involve no runtime overheads). There are many other advantages of using templates and they are discussed in detail later in this article. To illustrate the usefulness of templates, let us take an example from the C standard library. To get the absolute value of a number we need different functions, one for each type. For integers we use abs, for floating point numbers fabs, and for complex numbers cabs. If polymorphic facilities were available in C, such inventing of new names would not have been necessary (and life could have been easier for the programmer). How about using overloading in C++ for this problem? Consider:
  2. 2. int abs(int); long abs(long); double abs(double); complex abs(complex); Yes, in this case, we need not reinvent new names, but still almost same code is duplicated in these functions; so, overloading is not a very good solution. How about using overriding? No, it cannot help us in for this requirement since these functions differ in their argument and return type, and overriding requires that the signature remains the same. Using templates could elegantly solve this problem. Using function templates, it is enough to write generic code for one function: template <class T> T abs(T arg) { return ((arg < 0) ? –arg : arg); } With this definition, the compiler will take care of creating copies (known as template instantiation) for specific types as and when required in the program. For example, when given abs(12) or abs(doubleVar), the compiler is smart enough to instantiate (or make use of the one if already instantiated) the right function for that type and resolve it in the compile time itself. In the beginning of the article, we mentioned that templates started with the desire to quot;parameterizequot; the containers. Such classes are known as ‘class templates’. A simple example would be a stack container parameterized by type T instead of providing separate classes like int_stack, string_stack, double_stack etc: template <class T> class stack { // the following members remain the same stack(int start_size = 10); stack(const stack&); stack& operator=(const stack&); ~stack(); int is_empty() const; int is_full() const; // templatizing these members using T void push(const T& t); T& pop(); private: T* stack; // Note T* here int topOfStack; // following data members remain the same int size; }; Templates can provide readymade implementations even for day-to-day programming activities (for example, consider std::for_each function template in STL); hence it frees the programmer from reinventing the wheel and allows him to straightaway reuse what is available in templates. Templates make it possible to write truly reusable components that can be modified with little
  3. 3. difficulty, still retaining type safety (ensuring type safety is an important objective of strongly typed languages). Template Meta-programming Let us take another example to see from different perspective. An important advantage of C++ templates is its unimaginably expressive and powerful nature. Here is a simple (and well-known) example of template version of finding factorial of a number: template <int num> struct Factorial { static const int fact = num * Factorial < num - 1 > :: fact; }; // specialization for 0, which provides terminating condition template <> struct Factorial<0> { static const int fact = 1; }; int main() { std::cout<< quot;The factorial of 3 is: quot; << Factorial<3>::fact; } // output: // The factorial of 3 is: 6 Remember that template mechanism is a compile-time mechanism in C++. In this program, there is a template for Factorial with non-type parameter int. There is a template specialization of Factorial for value 0 - template instantiation is done for 3, 2, 1 and terminates at 0 as there is a specialization available. For finding the factorial of 3, with template instantiation, the value is found at compile-time itself! This approach of programming is known as meta-programming, which is an emerging programming approach in C++. Meta-programming is a difficult topic and it is possible to write sophisticated programs which do compile-time manipulations. Boost is a set of open-source libraries, mostly written based on meta-programming approach. The factorial example given in this section is just for introducing the topic and we’ll not cover it anymore in this article; if you are interested, please see the Boost website ( for more details. Advantages of Using Templates Templates abstract type information (and non-type information too) You can use primitive types, class types or templates themselves as arguments: in this way, templates offer maximum flexibility in their use. Consider: template <int lines, int columns> class screen { char ** buffer; explicit screen(lines, columns) { buffer = new char[lines * columns]; } // other members
  4. 4. }; typdef screen<24, 80> text_screen; type_screen my_screen; Here, the non-type arguments are used to specify the number of rows and columns in a screen. A typical text screen might be made up of 24 lines and 80 columns. If you want to change the dimensions of screen, you can instantiate a new screen type by providing new dimensions. In this way, the screen template offers flexibility in providing the dimensions of the screen. Templates provide readymade components for both generic and specific uses How will you design a container for a simple dictionary? Given a string as key (the word for which meaning needs to be found), a mapping should be provided to locate the list of strings (as meanings of the word). For this purpose, you can provide a new typedef of the standard map template provided in the C++ standard library: typedef map< string, list<string> > dictionary; A map template has a <key, value> pair and you can search for values using the key. In this instantiation of map template, string is the key type holding the word to be searched and a list<string> is the type that has the list of meanings for the words. So, this instantiation solves our problem. Since templates can take other templates as arguments, this becomes a powerful tool for design with minimal need to write your own code or to customize according to your need (though it is possible to customize STL containers and algorithms). Templates provide compact reusable code Template code can be very compact compared to the code written using conventional approach of writing reusable software using inheritance hierarchies in C++. For example, STL is a compact library if compared to a library providing similar functionality with conventional inheritance based approach. Problems with Templates Though the templates provide significant benefits in the form of writing reusable code, there are significant problems that can put even experienced C++ programmers into trouble. Here is a small list of problems in using templates. The syntax for using templates is clumsy The syntax for template is somewhat clumsy and for code of significant complexity sometimes makes the code very difficult to understand. Particularly the meta-programming techniques tend to result in quite complex and unreadable code. Difficulty in understanding compiler error messages The error messages for templates, in most of the cases, are very difficult to understand and comprehend. Even simple mistakes in template usage can result in incomprehensible error messages. Though the situation should improve with the compilers slowly maturing with better template support, the current state of the quality of the error messages that the compiler can emit is less than satisfactory. It takes considerable effort to write reusable components
  5. 5. Understanding and writing template code is complex simply because of the fact that writing reusable code is inherently difficult. Note that only writing template code that is difficult; using templates is quite easy. In fact, it is quite possible to use templates without understanding that they are in fact templates! For example, many of the C++ programmers use std::string without knowing that it is a template! std::string is a typedef of: std::basic_string< char, std::char_traits< char >, std::allocator< char > > Almost entire C++ standard library (only with some exceptions) make use of templates. Parameterized Types in Java and C# Type parameterization (known as ‘generics’ feature) is supported in many well known statically typed languages, including ML, Ada, Eiffel, Java and C#. In these languages, generics is meant for providing ‘type safe containers’. However, in C++, the support for templates is very sophisticated and entire libraries are often written using templates feature extensively. Also, the applications of templates in C++ are beyond the simple idea of writing type safe containers. For example, it is possible to write sophisticated meta-programs (an introduction was given in this article), but that is not possible with languages like Java or C#. In the next article In this article, we saw a technical overview of the powerful templates feature in C++. In the follow- up article next month, we’ll see various language features for supporting templates in C++. References [Gamma et al, 1994] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, “Design Patterns: Elements of Reusable Object-Oriented Software”, Addison-Wesley, 1994 S.G. Ganesh is a research engineer in Siemens (Corporate Technology). He has authored a book “Deep C” (ISBN 81-7656-501-6). You can reach him at