SlideShare uma empresa Scribd logo
1 de 3
Baixar para ler offline
Overview
                   Overview




Understanding C++
Templates                                                                             his article is a follow-up to the
In this article, we’ll learn the basic syntax and

                                                                             T
                                                                                      ‘An Introduction to C++
semantics of the features in the templates in C++ and                                 Templates’ article published in
                                                                                      the October issue of LFY. So,
write small programs.
                                                                                      without further ado, let’s get
                                                                        started.

                                                                        Class and function templates
                                                                        There are two kinds of templates: function
                                                                        templates and class templates. To define a
                                                                        template, use the template keyword with the
                                                                        template parameters given within ankle
                                                                        brackets, and provide the class or function
                                                                        definition after that. For example:

                                                                         // array_container is a ‘class template’
                                                                         template <class T>
                                                                         class array_container {
                                                                                   T arr[10];
                                                                                   // other members
                                                                         };


                                                                         // generic swap is a ‘function template’
                                                                         template <class Type>
                                                                         void swap(Type &t1, Type &t2) {
                                                                                   Type temp = t1;
                                                                                   t1 = t2;
                                                                                   t2 = temp;
                                                                         }


                                                                            The conventional names typically used for
                                                                        template-type arguments are T and Type, but
                                                                        it can be any valid variable name.

                                                                        Template instantiation
                                                                        We can ‘use’ the template by providing
                                                                        necessary arguments, which is known as
                                                                        instantiating the template. An instance
                                                                        created from that template is a template
                                                                        instantiation. For class templates, we have to
                                                                        explicitly provide the instantiation arguments.
                                                                        For function templates, we can explicitly
                                                                        provide the template arguments or else the


88   NOVEMBER 2007   |   LINUX FOR YOU   |   www.linuxforu.com



                                                                 CMYK
Overview



compiler will automatically infer the template arguments                       T arr[size];
from the function arguments.                                         public:
    For example, here is how we can instantiate the                            int getLength() {
array_container and swap templates:                                                      return size;
                                                                               }
 // type arguments are explicitly provided                                     // other members
 array_container<int> arr_int;                                       };


 float i = 10.0, j = 20.0;                                           array_container<float, 10> arr_flt;
 // compiler infers the type of argument as float and                cout<<“array size is “ << arr_flt.getLength();
 // implicitly instantiates swap<float>(float &, float &);           // prints: array size is 10
 swap(i, j);
 // or explicitly provide template arguments like this:
 // swap<float>(i, j);                                              Implicit instantiation and type inference
 cout<<“after swap : “<< i << “ “ << j;                             The implicit inference of function templates is very
 // prints after swap : 20 and 10                                   convenient to use; the users of the template need not even
                                                                    know that it is a template (well, in most cases), and use it
                                                                    as if it were an ordinary function. This is a powerful
Template parameters                                                 feature, particularly when used with function overloading.
Template parameters are of three types: type parameters,            We’ll look at a simple example for inference of template
non-type parameters and template-template parameters.               parameters here:
Type parameters are used for abstracting the type details
in data-structures and algorithms. Non-type parameters               // the types T and SIZE are implicitly inferred from the
are used for abstracting the values known at compile-time            // use of this function template
itself. A template itself can be passed as a parameter to            template<typename T, int SIZE>
another template, which is a template-template parameter.            int infer_size(T (*arr)[SIZE]) {
We’ve already seen an example for type parameters, and               return SIZE;
we’ll cover non-type parameters in the next section.                 }
Template-template parameters are not covered in this
article as it’s an advanced topic.                                   int main() {
    Type parameters can be declared with class or                    int int_arr[] = {0, 1} ;
typename keywords and both are equivalent. Using the                       char literal[] = “literal”;
keyword class for a template type parameter can be a little                cout<<“length of int_arr: “<<infer_size(&int_arr)<<endl;
confusing, since the keyword class is mainly used for                      cout<<“length of literal: “<<infer_size(&literal)<<endl;
declaring a class; so it is preferable to use the typename           }
keyword for type parameters. For example:
                                                                     // prints
 // instead of template <class T> use                                //        length of int_arr: 2
 template <typename T>                                               //        length of literal: 8
 class array_container;
                                                                        In this program, the type and non-type parameters are
Template non-type parameters                                        automatically inferred from the instantiation of infer_size.
Non-type parameters are used for abstracting constant               The first instantiation is for the integer array of Size 2. The
values in a template class. Non-type parameters cannot be           T in infer_size is inferred as int and SIZE as 2. Similarly,
of floating-point type. Also, the value of a non-type               for the string literal, it becomes char and 8.
parameter should be known at the compile-time itself as
templates are a compile-time mechanism and template                 Template specialisation
instantiation is done by the compiler.                                   A template is to provide the description for the generic
    In the array_container template we saw earlier, we              implementation of a class or a function. For specific types
abstracted the type of the array and hard-coded the size of         (or values, in case of non-type parameters), the template
the array. It will be flexible if we can change the size of the     is instantiated or specialised. For class and function
array for different uses. Non-type parameters come handy            templates, specialisation results in class and function
for purposes like this:                                             definitions. Such generated class and function definitions
                                                                    can be used just like any other class or function definitions
 template <class T, int size>                                       (they are ‘first class citizens’). If you want to provide a
 class array_container {                                            specific implementation for particular types (or values in


                                                                     www.linuxforu.com   |    LINUX FOR YOU   |   NOVEMBER 2007   89


                                                             CMYK
Overview



case of non-type arguments), you can explicitly provide a                      t1.swap(t2);
specialised implementation; this is known as explicit                  }
specialisation.
    In case an instantiation is needed for those particular            int main() {
types or values, instead of creating a class or function                       int i = 20, j = 10;
definition from the template, if any of the explicit                           // compiler instantiates swap<int>(int &, int &)
specialisations match, it will be used.                                        swap(i, j);
    Consider that the user-defined class my_vector has a               my_vector v1(20), v2(10);
member swap that provides an efficient implementation                          // however, for my_vector, the specialization is used
for swapping two my_vectors. If a swap function with two                       swap(v1, v2);
arguments passing my_vector instances are passed, we                   }
prefer to call my_vector::swap instead, using the code in
the general swap template. Here is how we can do it:                       When the explicit specialisation has one or more
                                                                      parameters that still depend on the type or non-type
 // generic swap is a ‘function template’                             parameters of the primary template, it is referred to as
 template <class Type>                                                partial specialisation.
 void swap(Type &t1, Type &t2) {                                           C++ templates is a very powerful feature, but it is also
         Type temp = t1;                                              complex and it takes time to learn the features and master
         t1 = t2;                                                     it. In this article, we had a brief overview of the features of
         t2 = temp;                                                   the templates in C++, which is a good starting point for
 }                                                                    exploring it further.

 // explicit specialization for swapping my_vector’s                   By: S.G. Ganesh is a research engineer in Siemens
 template <>                                                           (Corporate Technology). He has authored a book “Deep C”
 void swap(my_vector &t1, my_vector &t2) {                             (ISBN 81-7656-501-6). You can reach him at
         // call my_vector::swap for swapping two my_vector’s          sgganesh@gmail.com.




90    NOVEMBER 2007      |   LINUX FOR YOU   |   www.linuxforu.com



                                                                     CMYK

Mais conteúdo relacionado

Destaque (10)

Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Files in c++
Files in c++Files in c++
Files in c++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
file handling c++
file handling c++file handling c++
file handling c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 

Semelhante a C++ Templates 2

Semelhante a C++ Templates 2 (20)

An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
OOP - Templates
OOP - TemplatesOOP - Templates
OOP - Templates
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Generics
GenericsGenerics
Generics
 
Data structures and algorithms lab2
Data structures and algorithms lab2Data structures and algorithms lab2
Data structures and algorithms lab2
 
Savitch ch 17
Savitch ch 17Savitch ch 17
Savitch ch 17
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Templates1
Templates1Templates1
Templates1
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
TEMPLATES in C++
TEMPLATES in C++TEMPLATES in C++
TEMPLATES in C++
 
C presentation! BATRA COMPUTER CENTRE
C presentation! BATRA  COMPUTER  CENTRE C presentation! BATRA  COMPUTER  CENTRE
C presentation! BATRA COMPUTER CENTRE
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Function template
Function templateFunction template
Function template
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 

Mais de 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
 

Mais de 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
 

Último

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

C++ Templates 2

  • 1. Overview Overview Understanding C++ Templates his article is a follow-up to the In this article, we’ll learn the basic syntax and T ‘An Introduction to C++ semantics of the features in the templates in C++ and Templates’ article published in the October issue of LFY. So, write small programs. without further ado, let’s get started. Class and function templates There are two kinds of templates: function templates and class templates. To define a template, use the template keyword with the template parameters given within ankle brackets, and provide the class or function definition after that. For example: // array_container is a ‘class template’ template <class T> class array_container { T arr[10]; // other members }; // generic swap is a ‘function template’ template <class Type> void swap(Type &t1, Type &t2) { Type temp = t1; t1 = t2; t2 = temp; } The conventional names typically used for template-type arguments are T and Type, but it can be any valid variable name. Template instantiation We can ‘use’ the template by providing necessary arguments, which is known as instantiating the template. An instance created from that template is a template instantiation. For class templates, we have to explicitly provide the instantiation arguments. For function templates, we can explicitly provide the template arguments or else the 88 NOVEMBER 2007 | LINUX FOR YOU | www.linuxforu.com CMYK
  • 2. Overview compiler will automatically infer the template arguments T arr[size]; from the function arguments. public: For example, here is how we can instantiate the int getLength() { array_container and swap templates: return size; } // type arguments are explicitly provided // other members array_container<int> arr_int; }; float i = 10.0, j = 20.0; array_container<float, 10> arr_flt; // compiler infers the type of argument as float and cout<<“array size is “ << arr_flt.getLength(); // implicitly instantiates swap<float>(float &, float &); // prints: array size is 10 swap(i, j); // or explicitly provide template arguments like this: // swap<float>(i, j); Implicit instantiation and type inference cout<<“after swap : “<< i << “ “ << j; The implicit inference of function templates is very // prints after swap : 20 and 10 convenient to use; the users of the template need not even know that it is a template (well, in most cases), and use it as if it were an ordinary function. This is a powerful Template parameters feature, particularly when used with function overloading. Template parameters are of three types: type parameters, We’ll look at a simple example for inference of template non-type parameters and template-template parameters. parameters here: Type parameters are used for abstracting the type details in data-structures and algorithms. Non-type parameters // the types T and SIZE are implicitly inferred from the are used for abstracting the values known at compile-time // use of this function template itself. A template itself can be passed as a parameter to template<typename T, int SIZE> another template, which is a template-template parameter. int infer_size(T (*arr)[SIZE]) { We’ve already seen an example for type parameters, and return SIZE; we’ll cover non-type parameters in the next section. } Template-template parameters are not covered in this article as it’s an advanced topic. int main() { Type parameters can be declared with class or int int_arr[] = {0, 1} ; typename keywords and both are equivalent. Using the char literal[] = “literal”; keyword class for a template type parameter can be a little cout<<“length of int_arr: “<<infer_size(&int_arr)<<endl; confusing, since the keyword class is mainly used for cout<<“length of literal: “<<infer_size(&literal)<<endl; declaring a class; so it is preferable to use the typename } keyword for type parameters. For example: // prints // instead of template <class T> use // length of int_arr: 2 template <typename T> // length of literal: 8 class array_container; In this program, the type and non-type parameters are Template non-type parameters automatically inferred from the instantiation of infer_size. Non-type parameters are used for abstracting constant The first instantiation is for the integer array of Size 2. The values in a template class. Non-type parameters cannot be T in infer_size is inferred as int and SIZE as 2. Similarly, of floating-point type. Also, the value of a non-type for the string literal, it becomes char and 8. parameter should be known at the compile-time itself as templates are a compile-time mechanism and template Template specialisation instantiation is done by the compiler. A template is to provide the description for the generic In the array_container template we saw earlier, we implementation of a class or a function. For specific types abstracted the type of the array and hard-coded the size of (or values, in case of non-type parameters), the template the array. It will be flexible if we can change the size of the is instantiated or specialised. For class and function array for different uses. Non-type parameters come handy templates, specialisation results in class and function for purposes like this: definitions. Such generated class and function definitions can be used just like any other class or function definitions template <class T, int size> (they are ‘first class citizens’). If you want to provide a class array_container { specific implementation for particular types (or values in www.linuxforu.com | LINUX FOR YOU | NOVEMBER 2007 89 CMYK
  • 3. Overview case of non-type arguments), you can explicitly provide a t1.swap(t2); specialised implementation; this is known as explicit } specialisation. In case an instantiation is needed for those particular int main() { types or values, instead of creating a class or function int i = 20, j = 10; definition from the template, if any of the explicit // compiler instantiates swap<int>(int &, int &) specialisations match, it will be used. swap(i, j); Consider that the user-defined class my_vector has a my_vector v1(20), v2(10); member swap that provides an efficient implementation // however, for my_vector, the specialization is used for swapping two my_vectors. If a swap function with two swap(v1, v2); arguments passing my_vector instances are passed, we } prefer to call my_vector::swap instead, using the code in the general swap template. Here is how we can do it: When the explicit specialisation has one or more parameters that still depend on the type or non-type // generic swap is a ‘function template’ parameters of the primary template, it is referred to as template <class Type> partial specialisation. void swap(Type &t1, Type &t2) { C++ templates is a very powerful feature, but it is also Type temp = t1; complex and it takes time to learn the features and master t1 = t2; it. In this article, we had a brief overview of the features of t2 = temp; the templates in C++, which is a good starting point for } exploring it further. // explicit specialization for swapping my_vector’s By: S.G. Ganesh is a research engineer in Siemens template <> (Corporate Technology). He has authored a book “Deep C” void swap(my_vector &t1, my_vector &t2) { (ISBN 81-7656-501-6). You can reach him at // call my_vector::swap for swapping two my_vector’s sgganesh@gmail.com. 90 NOVEMBER 2007 | LINUX FOR YOU | www.linuxforu.com CMYK