SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

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 2013srikanthreddy004
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programmingijpla
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
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_outputAnil Dutt
 
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 1Ali 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 conceptsandeshjadhav28
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++DevangiParekh1
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programmingnmahi96
 

Was ist angesagt? (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
 

Andere mochten auch

[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - template[KOSSA] C++ Programming - 14th Study - template
[KOSSA] C++ Programming - 14th Study - templateSeok-joon Yun
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 

Andere mochten auch (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
 

Ähnlich wie 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.pptxBhushanLilhare
 
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.docxfaithxdunce63732
 
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 .pptxRowank2
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language Rowank2
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...Kevlin Henney
 
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 pptxinoe
 
Basic Concepts of C Language.pptx
Basic Concepts of C Language.pptxBasic Concepts of C Language.pptx
Basic Concepts of C Language.pptxKorbanMaheshwari
 
Basic Information About C language PDF
Basic Information About C language PDFBasic Information About C language PDF
Basic Information About C language PDFSuraj Das
 

Ähnlich wie 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
 

Mehr von Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh 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 EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh 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 ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh 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 DeckGanesh 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 LanguageGanesh 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 QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh 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 quizGanesh Samarthyam
 

Mehr von 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
 

Kürzlich hochgeladen

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Kürzlich hochgeladen (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

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.