SlideShare a Scribd company logo
1 of 32
Generic Programming (Generic Programming ( 泛型泛型程式程式
設計設計 ))
Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 ))
EMail:EMail: pinglunliao@gmail.compinglunliao@gmail.com
AgendaAgenda
ReusabilityReusability
Standard Template LibraryStandard Template Library
Class Templates (Class Templates ( 類別樣板類別樣板 ))
Standard Template Library(STL)Standard Template Library(STL)
It is not completely compatible in C++ ComIt is not completely compatible in C++ Com
pilerpiler
Template prototypes and definitions shoulTemplate prototypes and definitions shoul
d locate at the same file(*.h), except usingd locate at the same file(*.h), except using
"export" if compiler support it"export" if compiler support it
Using template classUsing template class
Stack<int> kernels; // create a stack of intStack<int> kernels; // create a stack of int
Stack<String> colonels; // a stack of String objectsStack<String> colonels; // a stack of String objects
Template<class T>Template<class T>
void simple(T t) { cout << t << "n"; }void simple(T t) { cout << t << "n"; }
simple(2); // generate void simple(int)simple(2); // generate void simple(int)
simple("two"); // generate void simple(char *)simple("two"); // generate void simple(char *)
 ExampleExample
 stackitemstackitem
Stack pointer-incorrect versionStack pointer-incorrect version
Stack<String> s; // original stackStack<String> s; // original stack
Stack<char *> st; // alternate stackStack<char *> st; // alternate stack
String po;String po;
Three described version for "String po;"Three described version for "String po;"
1.1. char *po; // cin >> po; errorchar *po; // cin >> po; error
2.2. char po[40];char po[40];
// template <class Type>// template <class Type>
// bool Stack<Type>::pop(Type &item)// bool Stack<Type>::pop(Type &item)
// { ...; item = items[--top]; ... }// { ...; item = items[--top]; ... }
// item is Lvalue, cannot be array name// item is Lvalue, cannot be array name
3.3. char *po = new char[40];char *po = new char[40];
// push to the same address, and pop the same address value// push to the same address, and pop the same address value
// pop outcome is always the last push data// pop outcome is always the last push data
Correct VersionCorrect Version
ExampleExample
stacktp1stacktp1
Template arrayTemplate array
Template is usually used in container classTemplate is usually used in container class
ArrayTP<ArrayTP<int,5>, 10> twodee;ArrayTP<ArrayTP<int,5>, 10> twodee;
int twodee[10][5];int twodee[10][5];
ExampleExample
arraytparraytp
Class Templates (Class Templates ( 類別樣板類別樣板 ))
template <class T> // Ttemplate <class T> // T 是樣板參數是樣板參數
class TStackclass TStack
{{
public:public:
TStack(int = 10) ;TStack(int = 10) ;
~TStack() { delete [] stackPtr ; }~TStack() { delete [] stackPtr ; }
bool Push(const T&);bool Push(const T&);
bool Pop(T&) ; // pop an element off the stackbool Pop(T&) ; // pop an element off the stack
bool isEmpty()const { return top == -1 ; }bool isEmpty()const { return top == -1 ; }
bool isFull() const { return top == size - 1 ; }bool isFull() const { return top == size - 1 ; }
private:private:
int size ; // Number of elements on Stackint size ; // Number of elements on Stack
int top ;int top ;
T* stackPtr ;T* stackPtr ;
};};
namespacenamespace
用來管理程式庫,解決名稱衝突的方法之一用來管理程式庫,解決名稱衝突的方法之一
。。
ExampleExample
UingNamespace.cppUingNamespace.cpp
ReusabilityReusability
Has-a relationshipHas-a relationship
Containment(or Composition)Containment(or Composition)
Private & protected inheritancePrivate & protected inheritance
Multiple inheritanceMultiple inheritance
Virtual base classVirtual base class
Template classTemplate class
ContainmentContainment
Containment (composition, layering) is a hContainment (composition, layering) is a h
as-a relationshipas-a relationship
class Studentclass Student
{{
private:private:
String name; // use a String object for namString name; // use a String object for nam
ee
ArrayDb scores; // use an ArrayDb object fArrayDb scores; // use an ArrayDb object f
or scoresor scores
};};
ContainmentContainment
ExampleExample
ArrayDb_studentcArrayDb_studentc
Containment or private inheritanceContainment or private inheritance
Has-a relationship is generated fromHas-a relationship is generated from
containment and private inheritancecontainment and private inheritance
In general, we can use containment toIn general, we can use containment to
build up "has-a" relationshipbuild up "has-a" relationship
Private inheritance involved in somePrivate inheritance involved in some
particular status, such as accessingparticular status, such as accessing
protected member, or redefined virtualprotected member, or redefined virtual
functionfunction
Public, protected, and privatePublic, protected, and private
inheritanceinheritance
Multiple inheritanceMultiple inheritance
Multiple inheritanceMultiple inheritance
ExampleExample
workermiworkermi
Ambiguous inheritanceAmbiguous inheritance
Type ConversionType Conversion
SingingWaiter obj;SingingWaiter obj;
Worker *pw = &obj; // ambiguousWorker *pw = &obj; // ambiguous
Worker *pw1 = (Waiter*)&obj; // the worker in waiterWorker *pw1 = (Waiter*)&obj; // the worker in waiter
Worker *pw2 = (Singer*)&obj; // the worker in singerWorker *pw2 = (Singer*)&obj; // the worker in singer
Inherit virtual base classInherit virtual base class
Using virtual base classUsing virtual base class
If class indirectly inherit from a virtual baseIf class indirectly inherit from a virtual base
class, the constructor in base class shouldclass, the constructor in base class should
be involved except taking implicit default cbe involved except taking implicit default c
onstructoronstructor
-SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int
v=Singer::other): Waiter(wk,p), Singer(wk,v=Singer::other): Waiter(wk,p), Singer(wk,
v){} // flawedv){} // flawed
-SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int
v=Singer::other):v=Singer::other): Worker(wk)Worker(wk),Waiter(wk,p),,Waiter(wk,p),
Singer(wk,v){} // OKSinger(wk,v){} // OK
Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))
有次序性的容器,容納單一型別的多個元素有次序性的容器,容納單一型別的多個元素
。。
索引動作索引動作 (indexing)(indexing)
下標下標 (subscript [])(subscript []) 運算子運算子
Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))
Object-Based DesignObject-Based Design
Object_BasedObject_Based
Object-Oriented DesignObject-Oriented Design
Object-OrientedObject-Oriented
Generic DesignGeneric Design
Without Inheritance: GenericWithout Inheritance: Generic
With Inheritance: Generic_InheritanceWith Inheritance: Generic_Inheritance
標準的標準的 ArrayArray 其實是個其實是個 VectorVector
Vector_DemoVector_Demo
DemoDemo
Array ClassArray ClassArray Class.dswArray Class.dsw
Container Classes and IteratorsContainer Classes and Iterators
Container classes (collection classes)Container classes (collection classes)
Classes designed to hold collections of objectsClasses designed to hold collections of objects
Provide services such as insertion, deletion, sProvide services such as insertion, deletion, s
earching, sorting, or testing an itemearching, sorting, or testing an item
Examples:Examples:
Arrays, stacks, queues, trees and linked listsArrays, stacks, queues, trees and linked lists
Iterator objects (iterators)Iterator objects (iterators)
Object that returns the next item of a collectionObject that returns the next item of a collection
(or performs some action on the next item)(or performs some action on the next item)
Can have several iterators per containerCan have several iterators per container
Book with multiple bookmarksBook with multiple bookmarks
STLSTL
ContainerContainer
IteratorIterator
AlgorithmAlgorithm
Function ObjectFunction Object
What is STLWhat is STL
SStandardtandard TTemplateemplate LLibrary.ibrary.
ANSI/ISO C++ANSI/ISO C++
Key PersonKey Person
Alexander A. Stepanov
STLSTL 的不同實現版本的不同實現版本
HP STLHP STL :這是第一個版本:這是第一個版本
P.J. Plauger STLP.J. Plauger STL
Rouge Wave STLRouge Wave STL
SGI STLSGI STL
STLportSTLport
Reference:Reference:
C++ STLC++ STL編程輕鬆入門基礎編程輕鬆入門基礎 1.41.4節節
Why do we learn STLWhy do we learn STL
第一版:史前時代第一版:史前時代 ---- 轉木取火轉木取火
採用大容量的靜態數組分配。採用大容量的靜態數組分配。
限定輸入的數據個數。限定輸入的數據個數。
採用動態內存分配。採用動態內存分配。
第二版:工業時代第二版:工業時代 ---- 組件化大生產組件化大生產
第三版:唯美主義的傑作第三版:唯美主義的傑作
Demo: WhyDemo: Why
Short Talk About STLShort Talk About STL
Container(Container( 容器容器 )) :各種資料結構如:各種資料結構如 vectorvector 、、 listlist
、、 dequedeque 、、 setset 、、 mapmap 。。
AlgorithmAlgorithm :各種常見的演算法如:各種常見的演算法如 sortsort 、、 searchsearch
、、 copycopy 、、 erase…erase… 等。等。
Iterators(Iterators( 迭代器迭代器 )) :扮演容器與演算法之間的膠:扮演容器與演算法之間的膠
著劑,所謂的「泛型指標」。著劑,所謂的「泛型指標」。
Functors(Functors( 仿函式仿函式 )) :行為類似函式,可做為演算:行為類似函式,可做為演算
法的某種策略法的某種策略 (policy)(policy) 。。
Adapters(Adapters( 配接器配接器 )) :一種用來修飾容器或仿函式:一種用來修飾容器或仿函式
或迭代器介面的東西,如或迭代器介面的東西,如 stackstack 。。
Allocators(Allocators( 配置器配置器 )) :負責空間配置與管理。:負責空間配置與管理。
STL StructureSTL Structure
建議閱讀書籍建議閱讀書籍
基礎基礎
C++ PrimerC++ Primer
C++C++ 程式語言經典增訂版程式語言經典增訂版
C++C++ 標準程式庫標準程式庫
進階進階
Effective STLEffective STL
泛型程式設計與泛型程式設計與 STLSTL
STLSTL 源碼剖析源碼剖析
ReferencesReferences
C++ How to Program 3rd.C++ How to Program 3rd.
STLSTL 源碼剖析源碼剖析
STLSTL中文站中文站
C++ Primer 3rdC++ Primer 3rd
C++C++ 教學範本教學範本
物件導向程式設計物件導向程式設計 hh
ttp://vr.me.ncku.edu.tw/courses/index-oop.htmttp://vr.me.ncku.edu.tw/courses/index-oop.htm

More Related Content

What's hot

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
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
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
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
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Introduction To Javascript
Introduction To JavascriptIntroduction To Javascript
Introduction To JavascriptRajat Pandit
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesisFranklin Chen
 
Architecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designArchitecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designJean Michel
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 

What's hot (19)

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
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
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Introduction To Javascript
Introduction To JavascriptIntroduction To Javascript
Introduction To Javascript
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis5-minute intro to property-based testing in Python with hypothesis
5-minute intro to property-based testing in Python with hypothesis
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Architecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designArchitecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented design
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 

Similar to Generic Programming

Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object javamha4
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8Raffi Khatchadourian
 

Similar to Generic Programming (20)

Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
core java
core javacore java
core java
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
About Python
About PythonAbout Python
About Python
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
Java session4
Java session4Java session4
Java session4
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
 

More from PingLun Liao

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言PingLun Liao
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹PingLun Liao
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人PingLun Liao
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For BioinformaticsPingLun Liao
 
C 檔案輸入與輸出
C 檔案輸入與輸出C 檔案輸入與輸出
C 檔案輸入與輸出PingLun Liao
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎PingLun Liao
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用PingLun Liao
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎PingLun Liao
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計PingLun Liao
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計PingLun Liao
 
Android introduction
Android introductionAndroid introduction
Android introductionPingLun Liao
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented ProgrammingPingLun Liao
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part IIPingLun Liao
 

More from PingLun Liao (20)

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人
 
陣列與指標
陣列與指標陣列與指標
陣列與指標
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For Bioinformatics
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
C 檔案輸入與輸出
C 檔案輸入與輸出C 檔案輸入與輸出
C 檔案輸入與輸出
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計
 
Java 網路程式
Java 網路程式Java 網路程式
Java 網路程式
 
Android introduction
Android introductionAndroid introduction
Android introduction
 
RESTful
RESTfulRESTful
RESTful
 
Web service
Web serviceWeb service
Web service
 
How toprogram
How toprogramHow toprogram
How toprogram
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented Programming
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part II
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Generic Programming

  • 1. Generic Programming (Generic Programming ( 泛型泛型程式程式 設計設計 )) Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 )) EMail:EMail: pinglunliao@gmail.compinglunliao@gmail.com
  • 3. Class Templates (Class Templates ( 類別樣板類別樣板 )) Standard Template Library(STL)Standard Template Library(STL) It is not completely compatible in C++ ComIt is not completely compatible in C++ Com pilerpiler Template prototypes and definitions shoulTemplate prototypes and definitions shoul d locate at the same file(*.h), except usingd locate at the same file(*.h), except using "export" if compiler support it"export" if compiler support it
  • 4. Using template classUsing template class Stack<int> kernels; // create a stack of intStack<int> kernels; // create a stack of int Stack<String> colonels; // a stack of String objectsStack<String> colonels; // a stack of String objects Template<class T>Template<class T> void simple(T t) { cout << t << "n"; }void simple(T t) { cout << t << "n"; } simple(2); // generate void simple(int)simple(2); // generate void simple(int) simple("two"); // generate void simple(char *)simple("two"); // generate void simple(char *)  ExampleExample  stackitemstackitem
  • 5. Stack pointer-incorrect versionStack pointer-incorrect version Stack<String> s; // original stackStack<String> s; // original stack Stack<char *> st; // alternate stackStack<char *> st; // alternate stack String po;String po; Three described version for "String po;"Three described version for "String po;" 1.1. char *po; // cin >> po; errorchar *po; // cin >> po; error 2.2. char po[40];char po[40]; // template <class Type>// template <class Type> // bool Stack<Type>::pop(Type &item)// bool Stack<Type>::pop(Type &item) // { ...; item = items[--top]; ... }// { ...; item = items[--top]; ... } // item is Lvalue, cannot be array name// item is Lvalue, cannot be array name 3.3. char *po = new char[40];char *po = new char[40]; // push to the same address, and pop the same address value// push to the same address, and pop the same address value // pop outcome is always the last push data// pop outcome is always the last push data
  • 7. Template arrayTemplate array Template is usually used in container classTemplate is usually used in container class ArrayTP<ArrayTP<int,5>, 10> twodee;ArrayTP<ArrayTP<int,5>, 10> twodee; int twodee[10][5];int twodee[10][5]; ExampleExample arraytparraytp
  • 8. Class Templates (Class Templates ( 類別樣板類別樣板 )) template <class T> // Ttemplate <class T> // T 是樣板參數是樣板參數 class TStackclass TStack {{ public:public: TStack(int = 10) ;TStack(int = 10) ; ~TStack() { delete [] stackPtr ; }~TStack() { delete [] stackPtr ; } bool Push(const T&);bool Push(const T&); bool Pop(T&) ; // pop an element off the stackbool Pop(T&) ; // pop an element off the stack bool isEmpty()const { return top == -1 ; }bool isEmpty()const { return top == -1 ; } bool isFull() const { return top == size - 1 ; }bool isFull() const { return top == size - 1 ; } private:private: int size ; // Number of elements on Stackint size ; // Number of elements on Stack int top ;int top ; T* stackPtr ;T* stackPtr ; };};
  • 10. ReusabilityReusability Has-a relationshipHas-a relationship Containment(or Composition)Containment(or Composition) Private & protected inheritancePrivate & protected inheritance Multiple inheritanceMultiple inheritance Virtual base classVirtual base class Template classTemplate class
  • 11. ContainmentContainment Containment (composition, layering) is a hContainment (composition, layering) is a h as-a relationshipas-a relationship class Studentclass Student {{ private:private: String name; // use a String object for namString name; // use a String object for nam ee ArrayDb scores; // use an ArrayDb object fArrayDb scores; // use an ArrayDb object f or scoresor scores };};
  • 13. Containment or private inheritanceContainment or private inheritance Has-a relationship is generated fromHas-a relationship is generated from containment and private inheritancecontainment and private inheritance In general, we can use containment toIn general, we can use containment to build up "has-a" relationshipbuild up "has-a" relationship Private inheritance involved in somePrivate inheritance involved in some particular status, such as accessingparticular status, such as accessing protected member, or redefined virtualprotected member, or redefined virtual functionfunction
  • 14. Public, protected, and privatePublic, protected, and private inheritanceinheritance
  • 18. Type ConversionType Conversion SingingWaiter obj;SingingWaiter obj; Worker *pw = &obj; // ambiguousWorker *pw = &obj; // ambiguous Worker *pw1 = (Waiter*)&obj; // the worker in waiterWorker *pw1 = (Waiter*)&obj; // the worker in waiter Worker *pw2 = (Singer*)&obj; // the worker in singerWorker *pw2 = (Singer*)&obj; // the worker in singer
  • 19. Inherit virtual base classInherit virtual base class
  • 20. Using virtual base classUsing virtual base class If class indirectly inherit from a virtual baseIf class indirectly inherit from a virtual base class, the constructor in base class shouldclass, the constructor in base class should be involved except taking implicit default cbe involved except taking implicit default c onstructoronstructor -SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int v=Singer::other): Waiter(wk,p), Singer(wk,v=Singer::other): Waiter(wk,p), Singer(wk, v){} // flawedv){} // flawed -SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int v=Singer::other):v=Singer::other): Worker(wk)Worker(wk),Waiter(wk,p),,Waiter(wk,p), Singer(wk,v){} // OKSinger(wk,v){} // OK
  • 21. Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 )) 有次序性的容器,容納單一型別的多個元素有次序性的容器,容納單一型別的多個元素 。。 索引動作索引動作 (indexing)(indexing) 下標下標 (subscript [])(subscript []) 運算子運算子
  • 22. Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 )) Object-Based DesignObject-Based Design Object_BasedObject_Based Object-Oriented DesignObject-Oriented Design Object-OrientedObject-Oriented Generic DesignGeneric Design Without Inheritance: GenericWithout Inheritance: Generic With Inheritance: Generic_InheritanceWith Inheritance: Generic_Inheritance 標準的標準的 ArrayArray 其實是個其實是個 VectorVector Vector_DemoVector_Demo
  • 23. DemoDemo Array ClassArray ClassArray Class.dswArray Class.dsw
  • 24. Container Classes and IteratorsContainer Classes and Iterators Container classes (collection classes)Container classes (collection classes) Classes designed to hold collections of objectsClasses designed to hold collections of objects Provide services such as insertion, deletion, sProvide services such as insertion, deletion, s earching, sorting, or testing an itemearching, sorting, or testing an item Examples:Examples: Arrays, stacks, queues, trees and linked listsArrays, stacks, queues, trees and linked lists Iterator objects (iterators)Iterator objects (iterators) Object that returns the next item of a collectionObject that returns the next item of a collection (or performs some action on the next item)(or performs some action on the next item) Can have several iterators per containerCan have several iterators per container Book with multiple bookmarksBook with multiple bookmarks
  • 26. What is STLWhat is STL SStandardtandard TTemplateemplate LLibrary.ibrary. ANSI/ISO C++ANSI/ISO C++ Key PersonKey Person Alexander A. Stepanov
  • 27. STLSTL 的不同實現版本的不同實現版本 HP STLHP STL :這是第一個版本:這是第一個版本 P.J. Plauger STLP.J. Plauger STL Rouge Wave STLRouge Wave STL SGI STLSGI STL STLportSTLport Reference:Reference: C++ STLC++ STL編程輕鬆入門基礎編程輕鬆入門基礎 1.41.4節節
  • 28. Why do we learn STLWhy do we learn STL 第一版:史前時代第一版:史前時代 ---- 轉木取火轉木取火 採用大容量的靜態數組分配。採用大容量的靜態數組分配。 限定輸入的數據個數。限定輸入的數據個數。 採用動態內存分配。採用動態內存分配。 第二版:工業時代第二版:工業時代 ---- 組件化大生產組件化大生產 第三版:唯美主義的傑作第三版:唯美主義的傑作 Demo: WhyDemo: Why
  • 29. Short Talk About STLShort Talk About STL Container(Container( 容器容器 )) :各種資料結構如:各種資料結構如 vectorvector 、、 listlist 、、 dequedeque 、、 setset 、、 mapmap 。。 AlgorithmAlgorithm :各種常見的演算法如:各種常見的演算法如 sortsort 、、 searchsearch 、、 copycopy 、、 erase…erase… 等。等。 Iterators(Iterators( 迭代器迭代器 )) :扮演容器與演算法之間的膠:扮演容器與演算法之間的膠 著劑,所謂的「泛型指標」。著劑,所謂的「泛型指標」。 Functors(Functors( 仿函式仿函式 )) :行為類似函式,可做為演算:行為類似函式,可做為演算 法的某種策略法的某種策略 (policy)(policy) 。。 Adapters(Adapters( 配接器配接器 )) :一種用來修飾容器或仿函式:一種用來修飾容器或仿函式 或迭代器介面的東西,如或迭代器介面的東西,如 stackstack 。。 Allocators(Allocators( 配置器配置器 )) :負責空間配置與管理。:負責空間配置與管理。
  • 31. 建議閱讀書籍建議閱讀書籍 基礎基礎 C++ PrimerC++ Primer C++C++ 程式語言經典增訂版程式語言經典增訂版 C++C++ 標準程式庫標準程式庫 進階進階 Effective STLEffective STL 泛型程式設計與泛型程式設計與 STLSTL STLSTL 源碼剖析源碼剖析
  • 32. ReferencesReferences C++ How to Program 3rd.C++ How to Program 3rd. STLSTL 源碼剖析源碼剖析 STLSTL中文站中文站 C++ Primer 3rdC++ Primer 3rd C++C++ 教學範本教學範本 物件導向程式設計物件導向程式設計 hh ttp://vr.me.ncku.edu.tw/courses/index-oop.htmttp://vr.me.ncku.edu.tw/courses/index-oop.htm