SlideShare a Scribd company logo
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:
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
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 (www.boost.org) 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
};

        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
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
sgganesh@gmail.com.

More Related Content

What's hot

C++ interview question
C++ interview questionC++ interview question
C++ interview question
Durgesh Tripathi
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
megersaoljira
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
ijpla
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
Unviersity of balochistan quetta
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
JAYA
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
Anil Dutt
 
Lecture 21 22
Lecture 21 22Lecture 21 22
Lecture 21 22
Najmul Hassan
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
Ali Raza Jilani
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
sandeshjadhav28
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
DevangiParekh1
 
Lk module3
Lk module3Lk module3
Lk module3
Krishna Nanda
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
C-PROGRAM
C-PROGRAMC-PROGRAM
C-PROGRAM
shahzadebaujiti
 

What's hot (20)

C++ interview question
C++ interview questionC++ interview question
C++ interview question
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
Lecture 21 22
Lecture 21 22Lecture 21 22
Lecture 21 22
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
 
C programming
C programmingC programming
C programming
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
structure and union
structure and unionstructure and union
structure and union
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
 
Lk module3
Lk module3Lk module3
Lk module3
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
C-PROGRAM
C-PROGRAMC-PROGRAM
C-PROGRAM
 

Viewers also liked

Generic programming
Generic programmingGeneric programming
Generic programming
Platonov Sergey
 
[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template
Seok-joon Yun
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 

Viewers also liked (6)

Generic programming
Generic programmingGeneric programming
Generic programming
 
[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template
 
Templates
TemplatesTemplates
Templates
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Oops ppt
Oops pptOops ppt
Oops ppt
 

Similar to An Introduction To C++Templates

Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
guestf0562b
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
BhushanLilhare
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
faithxdunce63732
 
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
Rowank2
 
Interview Questions For C Language .pptx
Interview Questions For C Language .pptxInterview Questions For C Language .pptx
Interview Questions For C Language .pptx
Rowank2
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language
Rowank2
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
rumanatasnim415
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
Kevlin Henney
 
C programming session7
C programming  session7C programming  session7
C programming session7
Keroles karam khalil
 
C programming session7
C programming  session7C programming  session7
C programming session7
Keroles karam khalil
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
C prog ppt
C prog pptC prog ppt
C prog ppt
xinoe
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
shubhra chauhan
 
Basic Concepts of C Language.pptx
Basic Concepts of C Language.pptxBasic Concepts of C Language.pptx
Basic Concepts of C Language.pptx
KorbanMaheshwari
 
Basic Information About C language PDF
Basic Information About C language PDFBasic Information About C language PDF
Basic Information About C language PDF
Suraj Das
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 

Similar to An Introduction To C++Templates (20)

Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
 
Interview Questions For C Language .pptx
Interview Questions For C Language .pptxInterview Questions For C Language .pptx
Interview Questions For C Language .pptx
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Basic Concepts of C Language.pptx
Basic Concepts of C Language.pptxBasic Concepts of C Language.pptx
Basic Concepts of C Language.pptx
 
Basic Information About C language PDF
Basic Information About C language PDFBasic Information About C language PDF
Basic Information About C language PDF
 
C++ Training
C++ TrainingC++ Training
C++ Training
 

More from Ganesh Samarthyam

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
Ganesh Samarthyam
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
Ganesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
Ganesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
Ganesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
Ganesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
Ganesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
Ganesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

An Introduction To C++Templates

  • 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. 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. 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 (www.boost.org) 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. }; 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. 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 sgganesh@gmail.com.