C++中的模板(template)

編譯器對聲明只做一件事情:記錄下來

編譯器一個時間只能夠編譯一個單元。

template <class T>//把函數做成模板
void swap(T& x,T& y){
    T temp = x;
    x = y;
    y = temp;
}

template <class T>
class Vector{
public:
    Vector(int);
    ~Vector();
    Vector(const Vector&);
    Vector& operator = (const Vector&);
    T& operator[](int);

private:
    T* m_elements;
    int m_size;
};

模板的用法:

template <class T,int bounds = 100>
class FixedVector{
public:
    FixedVector();
    T& operator[](int);
private:
    T elements[bounds];//fixed size array
};

舉例:

//具體的舉例
template<class A>
class Derived:public Base{};

template <class A>
class Derived:public List<A>{};

class SupervisorGroup:public List <Employee*>{}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章