SlideShare ist ein Scribd-Unternehmen logo
1 von 27
TEMPLATES
Michael Heron
Introduction
• In a previous lecture we talked very briefly about the idea
of parametric polymorphism.
• Being able to treat specific types of object independent of what
they actually are.
• In this lecture we are going to talk about C++’s templating
system.
• This lets us incorporate parametric polymorphism correctly in our
programs.
The Problem
• Say we want to create a basic kind of data structure.
• A queue
• A stack
• A hashmap
• How do we do that and still be able to deal with object
orientation?
• Answer is not immediately straightforward.
Java, Pre 1.5
• Many kinds of standard data structures exist as the
standard libraries in Java.
• Such as ArrayLists.
• Before version 1.5, the following syntax was used.
• Requires explicit casting of objects as they come off of the structure.
• Why?
• Polymorphism
Arraylist list = new ArrayList();
String str;
list.add (“Bing”);
list.add (“Bong”);
str = (String)list.get(0);
Java, 1.5+
• New versions of Java work with a different, more
demonic syntax.
• Explicit type information recorded along with the structure.
• No need for casting as things come off of the structure.
• How is such a thing achieved??
Arraylist<String> list = new ArrayList<String>();
String str;
list.add (“Bing”);
list.add (“Bong”);
str = list.get(0);
Generics/Templates
• The system in Java and C# is known as the
generics system.
• In C++, it’s called Templating.
• Both systems are roughly equivalent.
• Used for the same purpose, with various technical
differences.
• Templates more powerful than the Java/C# implementation.
• Provides a method for type-casting structures to permit
more elegant syntactic representation.
• Permits compile time checking of homogenous
consistency.
How Do They Work?
• Code we provide serves as a template for C++ to
generate specific instances of the code.
• Works like a structure that can deal with data at a family level of
granularity.
• Exists in two kinds:
• Function templates
• Class templates
Function Templates
• Function templates mimic a more flexible form of
method overloading.
• Overloading requires a method to be implemented for
all possible types of data.
• Function templates allow us to resolve that down
to a single template definition.
• Compiler can analyse provided parameters to
assess the function that must be created.
• Within limits… cannot interpret functionality where it
isn’t syntactically valid.
Function Templates
template <class T>
T add_nums(T a, T b);
#include <iostream>
#include "TemplateTest.h"
using namespace std;
template <typename T>
T add_nums(T num1, T num2)
{
return num1+num2;
}
int main() {
cout << add_nums ('a', 1) << endl;
return 0;
}
Ambiguity
• Because it is the compiler doing the work of interpreting
parameters, it cannot deal well with ambiguity.
• Where we say T, we must have it apply consistently across a
function call.
• We can ensure a certain kind of template being called by
type-casting the function call.
Ambiguous Function Call
#include <iostream>
#include "TemplateTest.h"
using namespace std;
template <typename T>
T add_nums(T num1, T num2)
{
return num1+num2;
}
int main() {
cout << add_nums (2.0f, 1) << endl;
return 0;
}
Non-Ambiguous Function Call
#include <iostream>
#include "TemplateTest.h"
using namespace std;
template <typename T>
T add_nums(T num1, T num2)
{
return num1+num2;
}
int main() {
cout << add_nums<float> (2.0f, 1) << endl;
return 0;
}
Multi-Type Functions
#include <iostream>
#include "TemplateTest.h"
using namespace std;
template <typename T, typename S>
T add_nums(T num1, S num2)
{
return num1+num2;
}
int main() {
float f;
f = add_nums<float, int> (5.0f, 3);
cout << f << endl;
return 0;
}
Class Templates
• In a similar way, we can create templates for C++
classes that are type agnostic.
• Again, the compiler will infer typing from context where
it possibility can.
• Good design in C++ separates out definition and
implementation.
• Into .h and .cpp files.
• Slight problem with doing this the way we have
done previously.
• It won’t work.
Class Templates
• Templates are not real code.
• Not as we understand it.
• It’s like a template letter in a word processor.
• Until the details are filled in, it’s not an actual letter.
• When separating out the definitions, the compiler
can’t deal with the T until it knows what types it’s
working with.
• The code doesn’t exist until you use it.
• This causes linking problems in the compiler.
Class Template Problems
• The complete definition for a function must be available at
the point of use.
• If the full definition isn’t available, the compiler assumes it has been
defined elsewhere.
• In the main program, it knows the type of the data type we
want to use.
• In the definition file, it doesn’t.
• So it never generates the appropriate code.
• Solution – inline functions.
A Stack Template
template <typename T>
class Stack {
private:
T *stack;
int current_size;
public:
Stack() :
stack (new T[100]),
current_size (0) {
}
void push(T thing) {
if (current_size == 100) {
return;
}
stack[current_size] = thing;
current_size += 1;
}
A Stack Template
T pop() {
T tmp;
current_size -= 1;
tmp = stack[current_size];
return tmp;
}
void clear() {
current_size = 0;
}
int query_size() {
return current_size;
}
~Stack() {
delete[] stack;
}
};
Using The Stack
#include <iostream>
#include <String>
#include "Stack.h"
using namespace std;
int main() {
Stack<int> *myStack;
myStack = new
Stack<int>();
myStack->push (100);
cout << myStack->pop()
<<
endl;
return 0;
}
#include <iostream>
#include <String>
#include "Stack.h"
using namespace std;
int main() {
Stack<string> *myStack;
myStack = new
Stack<string>();
myStack->push ("Hello");
cout << myStack->pop() <<
endl;
return 0;
}
Benefits of Templates
• Templates allow us to have classes and functions that
work independently of the data they use.
• No need to write a hundred different stacks, just write one using a
template.
• No significant performance overhead.
• It takes a little time for the compiler to generate the actionable
code, but it is not significant.
Qualified and Unqualified Names
• What does the typename keyword mean in C++?
• Have to go back quite a ways to explain this!
• Remember in our first header files, we’d often tell
them to use a namspace?
• To get access to the string class for one example.
• This is not good practice.
• We tell every class that uses the header to make use of
that namespace.
Qualified Names
• Qualified names are those that specifically note a
scope in a reference.
• For example, string is defined in std, thus:
• std::string
• std::cout
• Scope is independent of using a namespace
#include <iostream>
int main() {
std::cout << "Bing!" << std::endl;
return 0;
}
The Problem
template<class S>
void do_something()
{
S::x1 * x2;
}
What are we doing here?
Accessing a member variable called X1 in the parametrized class S?
Or…
Creating a pointer of type S::x1, with the name x2?
Typename resolves this problem.
One Last Thing…
• It’s often important to handle deep copies in templates.
• For the same reason it’s important in normal classes.
• Must include copy constructors and assignment operators
here.
• Remember the rules regarding these with reference to pointers and
others.
Deep Copies on Templates
Stack<T>(const Stack<T> &s) {
current_size = s.current_size;
stack = new T[100];
for (int i = 0; i < 100; i++) {
stack[i] = s.stack[i];
}
}
Remember these are designed to work on value objects and must be explicitly
de-referenced when working with pointers, like so:
Stack<string> *myStack, *stack2;
myStack = new Stack<string>;
stack2 = new Stack<string>(*myStack);
Deep Copies on Templates
Stack<T>& operator= (const Stack<T> &s) {
current_size = s.current_size;
delete[] stack;
stack = new T[100];
for (int i = 0; i < 100; i++) {
stack[i] = s.stack[i];
}
return (*this);
}
Summary
• Method overloading offers a degree of ad hoc
polymorphism.
• Combinations must be specified initially.
• Templates permit for parametric polymorphism.
• More complex, but a powerful way of creating generic data types.
• We’ll see the power of this in the next lecture.

Weitere ähnliche Inhalte

Was ist angesagt?

Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 

Was ist angesagt? (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Mit6 094 iap10_lec04
Mit6 094 iap10_lec04Mit6 094 iap10_lec04
Mit6 094 iap10_lec04
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Mit6 094 iap10_lec02
Mit6 094 iap10_lec02
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Mit6 094 iap10_lec03
Mit6 094 iap10_lec03Mit6 094 iap10_lec03
Mit6 094 iap10_lec03
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming Applications
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Introduction To TensorFlow | Deep Learning Using TensorFlow | CloudxLab
Introduction To TensorFlow | Deep Learning Using TensorFlow | CloudxLabIntroduction To TensorFlow | Deep Learning Using TensorFlow | CloudxLab
Introduction To TensorFlow | Deep Learning Using TensorFlow | CloudxLab
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 

Andere mochten auch

Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVA
Jai Marathe
 

Andere mochten auch (8)

2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVA
 
Use the @types, Luke
Use the @types, LukeUse the @types, Luke
Use the @types, Luke
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
 
Pizza compiler
Pizza compilerPizza compiler
Pizza compiler
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Expressjs basic to advance, power by Node.js
Expressjs basic to advance, power by Node.jsExpressjs basic to advance, power by Node.js
Expressjs basic to advance, power by Node.js
 

Ähnlich wie 2CPP15 - Templates

Ähnlich wie 2CPP15 - Templates (20)

Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates2
Templates2Templates2
Templates2
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
Modern C++
Modern C++Modern C++
Modern C++
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 

Mehr von Michael Heron

Mehr von Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

2CPP15 - Templates

  • 2. Introduction • In a previous lecture we talked very briefly about the idea of parametric polymorphism. • Being able to treat specific types of object independent of what they actually are. • In this lecture we are going to talk about C++’s templating system. • This lets us incorporate parametric polymorphism correctly in our programs.
  • 3. The Problem • Say we want to create a basic kind of data structure. • A queue • A stack • A hashmap • How do we do that and still be able to deal with object orientation? • Answer is not immediately straightforward.
  • 4. Java, Pre 1.5 • Many kinds of standard data structures exist as the standard libraries in Java. • Such as ArrayLists. • Before version 1.5, the following syntax was used. • Requires explicit casting of objects as they come off of the structure. • Why? • Polymorphism Arraylist list = new ArrayList(); String str; list.add (“Bing”); list.add (“Bong”); str = (String)list.get(0);
  • 5. Java, 1.5+ • New versions of Java work with a different, more demonic syntax. • Explicit type information recorded along with the structure. • No need for casting as things come off of the structure. • How is such a thing achieved?? Arraylist<String> list = new ArrayList<String>(); String str; list.add (“Bing”); list.add (“Bong”); str = list.get(0);
  • 6. Generics/Templates • The system in Java and C# is known as the generics system. • In C++, it’s called Templating. • Both systems are roughly equivalent. • Used for the same purpose, with various technical differences. • Templates more powerful than the Java/C# implementation. • Provides a method for type-casting structures to permit more elegant syntactic representation. • Permits compile time checking of homogenous consistency.
  • 7. How Do They Work? • Code we provide serves as a template for C++ to generate specific instances of the code. • Works like a structure that can deal with data at a family level of granularity. • Exists in two kinds: • Function templates • Class templates
  • 8. Function Templates • Function templates mimic a more flexible form of method overloading. • Overloading requires a method to be implemented for all possible types of data. • Function templates allow us to resolve that down to a single template definition. • Compiler can analyse provided parameters to assess the function that must be created. • Within limits… cannot interpret functionality where it isn’t syntactically valid.
  • 9. Function Templates template <class T> T add_nums(T a, T b); #include <iostream> #include "TemplateTest.h" using namespace std; template <typename T> T add_nums(T num1, T num2) { return num1+num2; } int main() { cout << add_nums ('a', 1) << endl; return 0; }
  • 10. Ambiguity • Because it is the compiler doing the work of interpreting parameters, it cannot deal well with ambiguity. • Where we say T, we must have it apply consistently across a function call. • We can ensure a certain kind of template being called by type-casting the function call.
  • 11. Ambiguous Function Call #include <iostream> #include "TemplateTest.h" using namespace std; template <typename T> T add_nums(T num1, T num2) { return num1+num2; } int main() { cout << add_nums (2.0f, 1) << endl; return 0; }
  • 12. Non-Ambiguous Function Call #include <iostream> #include "TemplateTest.h" using namespace std; template <typename T> T add_nums(T num1, T num2) { return num1+num2; } int main() { cout << add_nums<float> (2.0f, 1) << endl; return 0; }
  • 13. Multi-Type Functions #include <iostream> #include "TemplateTest.h" using namespace std; template <typename T, typename S> T add_nums(T num1, S num2) { return num1+num2; } int main() { float f; f = add_nums<float, int> (5.0f, 3); cout << f << endl; return 0; }
  • 14. Class Templates • In a similar way, we can create templates for C++ classes that are type agnostic. • Again, the compiler will infer typing from context where it possibility can. • Good design in C++ separates out definition and implementation. • Into .h and .cpp files. • Slight problem with doing this the way we have done previously. • It won’t work.
  • 15. Class Templates • Templates are not real code. • Not as we understand it. • It’s like a template letter in a word processor. • Until the details are filled in, it’s not an actual letter. • When separating out the definitions, the compiler can’t deal with the T until it knows what types it’s working with. • The code doesn’t exist until you use it. • This causes linking problems in the compiler.
  • 16. Class Template Problems • The complete definition for a function must be available at the point of use. • If the full definition isn’t available, the compiler assumes it has been defined elsewhere. • In the main program, it knows the type of the data type we want to use. • In the definition file, it doesn’t. • So it never generates the appropriate code. • Solution – inline functions.
  • 17. A Stack Template template <typename T> class Stack { private: T *stack; int current_size; public: Stack() : stack (new T[100]), current_size (0) { } void push(T thing) { if (current_size == 100) { return; } stack[current_size] = thing; current_size += 1; }
  • 18. A Stack Template T pop() { T tmp; current_size -= 1; tmp = stack[current_size]; return tmp; } void clear() { current_size = 0; } int query_size() { return current_size; } ~Stack() { delete[] stack; } };
  • 19. Using The Stack #include <iostream> #include <String> #include "Stack.h" using namespace std; int main() { Stack<int> *myStack; myStack = new Stack<int>(); myStack->push (100); cout << myStack->pop() << endl; return 0; } #include <iostream> #include <String> #include "Stack.h" using namespace std; int main() { Stack<string> *myStack; myStack = new Stack<string>(); myStack->push ("Hello"); cout << myStack->pop() << endl; return 0; }
  • 20. Benefits of Templates • Templates allow us to have classes and functions that work independently of the data they use. • No need to write a hundred different stacks, just write one using a template. • No significant performance overhead. • It takes a little time for the compiler to generate the actionable code, but it is not significant.
  • 21. Qualified and Unqualified Names • What does the typename keyword mean in C++? • Have to go back quite a ways to explain this! • Remember in our first header files, we’d often tell them to use a namspace? • To get access to the string class for one example. • This is not good practice. • We tell every class that uses the header to make use of that namespace.
  • 22. Qualified Names • Qualified names are those that specifically note a scope in a reference. • For example, string is defined in std, thus: • std::string • std::cout • Scope is independent of using a namespace #include <iostream> int main() { std::cout << "Bing!" << std::endl; return 0; }
  • 23. The Problem template<class S> void do_something() { S::x1 * x2; } What are we doing here? Accessing a member variable called X1 in the parametrized class S? Or… Creating a pointer of type S::x1, with the name x2? Typename resolves this problem.
  • 24. One Last Thing… • It’s often important to handle deep copies in templates. • For the same reason it’s important in normal classes. • Must include copy constructors and assignment operators here. • Remember the rules regarding these with reference to pointers and others.
  • 25. Deep Copies on Templates Stack<T>(const Stack<T> &s) { current_size = s.current_size; stack = new T[100]; for (int i = 0; i < 100; i++) { stack[i] = s.stack[i]; } } Remember these are designed to work on value objects and must be explicitly de-referenced when working with pointers, like so: Stack<string> *myStack, *stack2; myStack = new Stack<string>; stack2 = new Stack<string>(*myStack);
  • 26. Deep Copies on Templates Stack<T>& operator= (const Stack<T> &s) { current_size = s.current_size; delete[] stack; stack = new T[100]; for (int i = 0; i < 100; i++) { stack[i] = s.stack[i]; } return (*this); }
  • 27. Summary • Method overloading offers a degree of ad hoc polymorphism. • Combinations must be specified initially. • Templates permit for parametric polymorphism. • More complex, but a powerful way of creating generic data types. • We’ll see the power of this in the next lecture.