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

Generic Programming

  • 1.
    Generic Programming (GenericProgramming ( 泛型泛型程式程式 設計設計 )) Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 )) EMail:EMail: pinglunliao@gmail.compinglunliao@gmail.com
  • 2.
  • 3.
    Class Templates (ClassTemplates ( 類別樣板類別樣板 )) 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 classUsingtemplate 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 versionStackpointer-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
  • 6.
  • 7.
    Template arrayTemplate array Templateis 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 (ClassTemplates ( 類別樣板類別樣板 )) 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 ; };};
  • 9.
  • 10.
    ReusabilityReusability Has-a relationshipHas-a relationship Containment(orComposition)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 };};
  • 12.
  • 13.
    Containment or privateinheritanceContainment 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, andprivatePublic, protected, and private inheritanceinheritance
  • 15.
  • 16.
  • 17.
  • 18.
    Type ConversionType Conversion SingingWaiterobj;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 baseclassInherit virtual base class
  • 20.
    Using virtual baseclassUsing 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 (Arrayclass ( 模擬語言內建的陣列模擬語言內建的陣列 )) 有次序性的容器,容納單一型別的多個元素有次序性的容器,容納單一型別的多個元素 。。 索引動作索引動作 (indexing)(indexing) 下標下標 (subscript [])(subscript []) 運算子運算子
  • 22.
    Array class (Arrayclass ( 模擬語言內建的陣列模擬語言內建的陣列 )) 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 ClassArrayClass.dswArray Class.dsw
  • 24.
    Container Classes andIteratorsContainer 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
  • 25.
  • 26.
    What is STLWhatis STL SStandardtandard TTemplateemplate LLibrary.ibrary. ANSI/ISO C++ANSI/ISO C++ Key PersonKey Person Alexander A. Stepanov
  • 27.
    STLSTL 的不同實現版本的不同實現版本 HP STLHPSTL :這是第一個版本:這是第一個版本 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 welearn STLWhy do we learn STL 第一版:史前時代第一版:史前時代 ---- 轉木取火轉木取火 採用大容量的靜態數組分配。採用大容量的靜態數組分配。 限定輸入的數據個數。限定輸入的數據個數。 採用動態內存分配。採用動態內存分配。 第二版:工業時代第二版:工業時代 ---- 組件化大生產組件化大生產 第三版:唯美主義的傑作第三版:唯美主義的傑作 Demo: WhyDemo: Why
  • 29.
    Short Talk AboutSTLShort 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( 配置器配置器 )) :負責空間配置與管理。:負責空間配置與管理。
  • 30.
  • 31.
    建議閱讀書籍建議閱讀書籍 基礎基礎 C++ PrimerC++ Primer C++C++程式語言經典增訂版程式語言經典增訂版 C++C++ 標準程式庫標準程式庫 進階進階 Effective STLEffective STL 泛型程式設計與泛型程式設計與 STLSTL STLSTL 源碼剖析源碼剖析
  • 32.
    ReferencesReferences C++ How toProgram 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