SlideShare a Scribd company logo
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.

More Related Content

What's hot

Lecture 3
Lecture 3Lecture 3
Lecture 3
Muhammad Fayyaz
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Muhammad Fayyaz
 
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
 
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
 
Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Mit6 094 iap10_lec02
Mit6 094 iap10_lec02
Tribhuwan Pant
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
Neeraj Kaushik
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming Applications
Debasish Ghosh
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
OCaml
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Muhammad Fayyaz
 
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
CP-Union
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
Knoldus Inc.
 
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
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++
Khushal Mehta
 

What's hot (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++
 

Viewers also liked

2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
Michael Heron
 
Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVAJai Marathe
 
Use the @types, Luke
Use the @types, LukeUse the @types, Luke
Use the @types, Luke
Brooklyn Zelenka
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
Scott Wlaschin
 
Pizza compiler
Pizza compilerPizza compiler
Pizza compiler
Sander Mak (@Sander_Mak)
 
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.js
Caesar Chi
 

Viewers also liked (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
 

Similar to 2CPP15 - Templates

Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Templates2
Templates2Templates2
Templates2
zindadili
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
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
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Sergey Platonov
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Modern C++
Modern C++Modern C++
Modern C++
Michael Clark
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ssuser0c24d5
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
nilesh405711
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
YashpalYadav46
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
DevliNeeraj
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
FarazKhan89093
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
Saiganesh124618
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
Sasha Goldshtein
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 

Similar to 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
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented ProgrammingTEMPLATES in C++ are one of important topics in Object Oriented Programming
TEMPLATES in C++ are one of important topics in Object Oriented Programming
 
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
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael 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 Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael 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 Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
Michael Heron
 

More from 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
 

Recently uploaded

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 

Recently uploaded (20)

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 

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.