SlideShare a Scribd company logo
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 1
Zaar Hai
 
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
 
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 Python
Sujith 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 sharma
Sandesh Sharma
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
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 hypothesis
Franklin 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 Python
Sujith Kumar
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
Sasha Goldshtein
 

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 Concepts
mdfkhan625
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael 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
Derek 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 2009
Martin Odersky
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
mha4
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 
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 8Introduction to new features in java 8
Introduction to new features in java 8
Raffi Khatchadourian
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
SHIBDASDUTTA
 
Java session4
Java session4Java session4
Java session4
Jigarthacker
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
Fahad A. Shaikh
 

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
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
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
 
陣列與指標
陣列與指標陣列與指標
陣列與指標
PingLun Liao
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For Bioinformatics
PingLun Liao
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
PingLun Liao
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun 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
 
Java 網路程式
Java 網路程式Java 網路程式
Java 網路程式
PingLun Liao
 
Android introduction
Android introductionAndroid introduction
Android introduction
PingLun Liao
 
RESTful
RESTfulRESTful
RESTful
PingLun Liao
 
Web service
Web serviceWeb service
Web service
PingLun Liao
 
How toprogram
How toprogramHow toprogram
How toprogram
PingLun Liao
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented Programming
PingLun Liao
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part II
PingLun 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

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 

Recently uploaded (20)

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

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