函数模板和类模板

来源:互联网 发布:单片机流水灯实验报告 编辑:程序博客网 时间:2024/04/30 22:33
#include <iostream>         
using namespace std;
template <typename T>
void swapNum(T & a,T & b)    //函数模板
{
    T temp = a;
    a = b;
    b = temp;
}
template <typename T,int size>
void display(T a)
{
    for(int i=0;i<size;i++)
        cout<<a<<endl;

}                              //函数模板


template<typename T,int KSize,int KVal> //类模板
class MyArray
{
public:
    MyArray();
    ~MyArray()
    {
        delete []m_pArr;
        m_pArr=NULL;
    }
    void display();
private:
    T *m_pArr;

};


template<typename T,int KSize,int KVal>
MyArray<T,KSize,KVal>::MyArray()
{
    m_pArr=new T[KSize];
    for(int i=0;i<KSize;i++)
        m_pArr[i]=KVal;

}


template<typename T,int KSize,int KVal>
void MyArray<T,KSize,KVal>::display()
{
    for(int i=0;i<KSize;i++)
    {
        cout<<m_pArr[i]<<endl;
    }

}

int main(void)
{
    int x = 10;                     ///////////////
    int y = 20;
    //swapNum(x,y);  这样也正确
    swapNum<int>(x,y);  
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    char b='b';
    display<char,5>(b);             ///////////////

    MyArray<int,5,6> arr;
    arr.display();
    system("pause");
    return 0;

}

以下是VS 2008 运行结果



注意:类模板因为许多的原因目前没法编译分离,即不能分开在.h声明和在.cpp定义函数,所以.h文件需要包含所有的类模板声明定义。

1 0
原创粉丝点击