Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

10-Generic and Templates #13

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Generic Functions

Code Reuse 的另一種發揮 設想今天需要使用不同名稱但相同功能的function去對應不同的arg

int abs(int x) { return (x>0)?x:-x; }
int fabs(float x) { return (x>0)?x:-x; }

這種方式會造成code重複,最差的一種方式,且取名困難不好記

然而使用Overloading也同樣需要寫多次

int abs(int x) { return (x>0)?x:-x; }
int abs(float x) { return (x>0)?x:-x; }

當function內容一樣但arg的資料型態不同時 這時候就可以使用Template實現通用函數Generic Functions

template <typename T1, typename T2> 或是 template <class T>

When you use typename it's more readable.

template<typename T>
T abs(T x){return (x>0)? x:-x;}

int main()
{
    int a =abs<int>(3); 
    return 0;
}

Generic Class

今天你也可能為了不同的member type創立不同的class

class char_stack{ char data[10] ;....} ;
class int_stack {int data[10]; ...} ;
class complex_stack{complex data[10]; ....};

這時候一樣可以使用template創立Generic Class

template<typename T>
class stack{
private:
    T data[10];

public:
    T pop(){}
};

int main()
{
    stack<float>s1;
    return 0;
}

定義在類別樣板外的成員函數template的使用

template<typename T>
class stack{
private:
    T data[10];
    int top, size;

public:
    void push(T x);
};

//原始void stack::push(T x) { data[++top] = x; }
//void stack<T>::push(T x) {data[++top] = x ; }

template <typename T>
void stack<T>::push(T x) {data[++top] = x ; }

上方一樣要使用template <typename T>