Generic Programming

32
Generic Programming ( Generic Programming ( 泛泛 泛泛 程程程 程程程 ) ) Lecturer: Liao Ping-Lun ( Lecturer: Liao Ping-Lun ( 程程程 程程程 ) ) EMail: EMail: [email protected] [email protected]

Transcript of Generic Programming

Page 1: Generic Programming

Generic Programming (Generic Programming ( 泛型泛型程式程式設計設計 ))

Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 ))EMail: EMail: [email protected]@gmail.com

Page 2: Generic Programming

AgendaAgenda

ReusabilityReusabilityStandard Template LibraryStandard Template Library

Page 3: Generic Programming

Class Templates (Class Templates ( 類別樣板類別樣板 ))Standard Template Library(STL)Standard Template Library(STL)It is not completely compatible in C++ CoIt is not completely compatible in C++ CompilermpilerTemplate prototypes and definitions shoTemplate prototypes and definitions should locate at the same file(*.h), except usuld locate at the same file(*.h), except using "export" if compiler support iting "export" if compiler support it

Page 4: Generic Programming

Using template classUsing template class

Stack<int> kernels; // create a stack of intStack<int> kernels; // create a stack of intStack<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

Page 5: Generic Programming

Stack pointer-incorrect versionStack pointer-incorrect version

Stack<String> s; // original stackStack<String> s; // original stackStack<char *> st; // alternate stackStack<char *> st; // alternate stackString 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; error2.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

Page 6: Generic Programming

Correct VersionCorrect Version

ExampleExamplestacktp1stacktp1

Page 7: Generic Programming

Template arrayTemplate array

Template is usually used in container classTemplate is usually used in container classArrayTP<ArrayTP<int,5>, 10> twodee;ArrayTP<ArrayTP<int,5>, 10> twodee;int twodee[10][5];int twodee[10][5];

ExampleExamplearraytparraytp

Page 8: Generic Programming

Class Templates (Class Templates ( 類別樣板類別樣板 ))template <class T> // T template <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 stackbool 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 Stackint top ; int top ; T* stackPtr ; T* stackPtr ;

};};

Page 9: Generic Programming

namespacenamespace

用來管理程式庫,解決名稱衝突的方法之一。用來管理程式庫,解決名稱衝突的方法之一。ExampleExample

UingNamespace.cppUingNamespace.cpp

Page 10: Generic Programming

ReusabilityReusability

Has-a relationshipHas-a relationshipContainment(or Composition)Containment(or Composition)Private & protected inheritancePrivate & protected inheritanceMultiple inheritanceMultiple inheritanceVirtual base classVirtual base classTemplate classTemplate class

Page 11: Generic Programming

ContainmentContainment

Containment (composition, layering) is a Containment (composition, layering) is a has-a relationshiphas-a relationship

class Studentclass Student{{ private:private: String name; // use a String object for naString name; // use a String object for na

meme ArrayDb scores; // use an ArrayDb object fArrayDb scores; // use an ArrayDb object f

or scoresor scores};};

Page 12: Generic Programming

ContainmentContainment

ExampleExampleArrayDb_studentcArrayDb_studentc

Page 13: Generic Programming

Containment or private Containment or private inheritanceinheritance

Has-a relationship is generated from Has-a relationship is generated from containment and private inheritancecontainment and private inheritance

In general, we can use containment In general, we can use containment to build up "has-a" relationshipto build up "has-a" relationship

Private inheritance involved in some Private inheritance involved in some particular status, such as accessing particular status, such as accessing protected member, or redefined protected member, or redefined virtual functionvirtual function

Page 14: Generic Programming

Public, protected, and private Public, protected, and private inheritanceinheritance

Page 15: Generic Programming

Multiple inheritanceMultiple inheritance

Page 16: Generic Programming

Multiple inheritanceMultiple inheritance

ExampleExampleworkermiworkermi

Page 17: Generic Programming

Ambiguous inheritanceAmbiguous inheritance

Page 18: Generic Programming

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 waiterWorker *pw2 = (Singer*)&obj; // the worker in singerWorker *pw2 = (Singer*)&obj; // the worker in singer

Page 19: Generic Programming

Inherit virtual base classInherit virtual base class

Page 20: Generic Programming

Using virtual base classUsing virtual base class

If class indirectly inherit from a virtual baIf class indirectly inherit from a virtual base class, the constructor in base class shse class, the constructor in base class should be involved except taking implicit dould be involved except taking implicit default constructorefault constructor

-SingingWaiter(const Worker &wk, int p=0, i-SingingWaiter(const Worker &wk, int p=0, int v=Singer::other): Waiter(wk,p), Singernt v=Singer::other): Waiter(wk,p), Singer(wk,v){} // flawed(wk,v){} // flawed

-SingingWaiter(const Worker &wk, int p=0, i-SingingWaiter(const Worker &wk, int p=0, int v=Singer::other): nt v=Singer::other): Worker(wk)Worker(wk),Waiter(w,Waiter(wk,p), Singer(wk,v){} // OKk,p), Singer(wk,v){} // OK

Page 21: Generic Programming

Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))

有次序性的容器,容納單一型別的多個元素。有次序性的容器,容納單一型別的多個元素。索引動作索引動作 (indexing)(indexing)下標下標 (subscript [])(subscript []) 運算子運算子

Page 22: Generic Programming

Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))

Object-Based DesignObject-Based DesignObject_BasedObject_Based

Object-Oriented DesignObject-Oriented DesignObject-OrientedObject-Oriented

Generic DesignGeneric DesignWithout Inheritance: GenericWithout Inheritance: GenericWith Inheritance: Generic_InheritanceWith Inheritance: Generic_Inheritance

標準的 標準的 Array Array 其實是個 其實是個 VectorVectorVector_DemoVector_Demo

Page 23: Generic Programming

DemoDemoArray ClassArray Class\Array Class.dsw\Array Class.dsw

Page 24: Generic Programming

Container Classes and IteratContainer Classes and Iteratorsors

Container classes (collection classes)Container classes (collection classes)Classes designed to hold collections of objectsClasses designed to hold collections of objectsProvide services such as insertion, deletion, seProvide services such as insertion, deletion, searching, sorting, or testing an itemarching, sorting, or testing an itemExamples: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 collectioObject that returns the next item of a collection (or performs some action on the next item)n (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 bookmarksEach iterator maintains its own “position” inEach iterator maintains its own “position” informationformationDiscussed further in chapter 20Discussed further in chapter 20

Page 25: Generic Programming

STLSTL

ContainerContainerIteratorIteratorAlgorithmAlgorithmFunction ObjectFunction Object

Page 26: Generic Programming

What is STLWhat is STL

SStandard tandard TTemplate emplate LLibrary.ibrary.

ANSI/ISO C++ANSI/ISO C++

Key PersonKey Person

Alexander A. Stepanov

Page 27: Generic Programming

STLSTL 的不同實現版本的不同實現版本HP STLHP STL :這是第一個版本:這是第一個版本

P.J. Plauger STLP.J. Plauger STLRouge Wave STLRouge Wave STLSGI STLSGI STL

STLportSTLportReference:Reference:

C++ STLC++ STL編程輕鬆入門基礎 編程輕鬆入門基礎 1.41.4節節

Page 28: Generic Programming

Why do we learn STLWhy do we learn STL

第一版:史前時代第一版:史前時代 ---- 轉木取火轉木取火採用大容量的靜態數組分配。 採用大容量的靜態數組分配。 限定輸入的數據個數。 限定輸入的數據個數。 採用動態內存分配。 採用動態內存分配。

第二版:工業時代第二版:工業時代 ---- 組件化大生產組件化大生產 第三版:唯美主義的傑作第三版:唯美主義的傑作Demo: WhyDemo: Why

Page 29: Generic Programming

Short Talk About STLShort Talk About STL

Container(Container( 容器容器 )) :各種資料結構如:各種資料結構如 vectorvector 、、 lislistt 、、 dequedeque 、、 setset 、、 mapmap 。。AlgorithmAlgorithm :各種常見的演算法如:各種常見的演算法如 sortsort 、、 searchsearch 、、copycopy 、、 erase…erase… 等。等。Iterators(Iterators( 迭代器迭代器 )) :扮演容器與演算法之間的膠:扮演容器與演算法之間的膠著劑,所謂的「泛型指標」。著劑,所謂的「泛型指標」。Functors(Functors( 仿函式仿函式 )) :行為類似函式,可做為演算:行為類似函式,可做為演算法的某種策略法的某種策略 (policy)(policy) 。。Adapters(Adapters( 配接器配接器 )) :一種用來修飾容器或仿函式:一種用來修飾容器或仿函式或迭代器介面的東西,如或迭代器介面的東西,如 stackstack 。。Allocators(Allocators( 配置器配置器 )) :負責空間配置與管理。:負責空間配置與管理。

Page 30: Generic Programming

STL StructureSTL Structure

Page 31: Generic Programming

建議閱讀書籍建議閱讀書籍基礎基礎

C++ PrimerC++ PrimerC++ C++ 程式語言經典增訂版 程式語言經典增訂版 C++ C++ 標準程式庫標準程式庫

進階進階Effective STLEffective STL泛型程式設計與 泛型程式設計與 STLSTLSTL STL 源碼剖析源碼剖析

Page 32: Generic Programming

ReferencesReferences

C++ How to Program 3rd.C++ How to Program 3rd.STL STL 源碼剖析源碼剖析STLSTL中文站中文站C++ Primer 3rdC++ Primer 3rdC++ C++ 教學範本教學範本物件導向程式設計物件導向程式設計 hhttp://vr.me.ncku.edu.tw/courses/index-ottp://vr.me.ncku.edu.tw/courses/index-oop.htmop.htm