SlideShare une entreprise Scribd logo
1  sur  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.

Contenu connexe

Tendances

Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil 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 sharmaSandesh 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!Kel Cecil
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsDebasish Ghosh
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
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 PythonCP-Union
 
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 | CloudxLabCloudxLab
 
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++Khushal Mehta
 

Tendances (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++
 

En vedette

2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVAJai Marathe
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeScott Wlaschin
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
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.jsCaesar Chi
 

En vedette (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
 

Similaire à 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
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
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 SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 

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

Dernier

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Dernier (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

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.