模板应用例子

模板函数

#include <iostream>
#include <cstdlib>

using namespace std;

template<class T> //定义声明模板函数
T func(T n)
{
    T result;
    result = n * n + 5;
}

int main()
{
    func(5);
    cout << "func(5)=" << func(5) << endl;
    cout << "func(5.5)=" << func(5.5) << endl;
}

非类型参数的函数模板

#include <iostream>
#include <cstdlib>

using namespace std;
//非类型参数的函数模板

template <class arrayType, int array_size> 
void showArray(arrayType (&array)[array_size])
{
    int i;
    for(i=0;i<array_size;i++){
        cout << i << " " << array[i] << endl;            
    }
}

int main()
{
    int a[] = {1,2,3,4,5};
    showArray(a);
    float b[] = {2.5,25.2,44.5,66.2};
    showArray(b);
}

类模板

#include <iostream>
#include <cstdlib>

using namespace std;

template <class type>
class function //声明类模板
{
    private:
        type y;
    public:
        function(type x){//带入模板形式参数
            y=x;
        }
        void show(){
            cout << "y=" << y << endl;
        }

};

int main()
{
    function<int> fun1(1);
    fun1.show();
    function<float> fun2(2.99);
    fun2.show();
    function<char> fun3('a');
    fun3.show();
}

堆栈类模板

#include <iostream>
#include <cstdlib>

using namespace std;

template <class Type = int,int size = 5>
class Stack
{
    private:
        Type st[size];
        int top;
    public:
        Stack(){
            top = -1;
        }
        void push(Type data);
        Type pop();
        int getNum(){
            return top+1;
        }
};

template <class Type, int size>
void Stack<Type,size> :: push(Type data)
{
    if((top+1)>(size-1)){
        cout << "man!"<< endl;
    }
    else {
        st[++top] = data;
    }
}

template <class Type, int size>
Type Stack<Type, size> :: pop()
{
    return st[top--];
}

int main()
{
    Stack <> stk1;
    stk1.push(1);
    stk1.push(2);
    stk1.push(3);
    while (stk1.getNum())
    {
        cout << "stk1:" << stk1.pop() << endl;
    }
    cout << "stk1 num:" << stk1.getNum() << endl;
    Stack <float> stk2;
    stk2.push(1.2);
    stk2.push(2);
    stk2.push(3.6);
    while (stk2.getNum())
    {
        cout << "stk2:" << stk2.pop() << endl;
    }
    cout << "stk2 num:" << stk2.getNum() << endl;

    Stack <char*,2> stk3;
    stk3.push("aaa");
    stk3.push("bbb");
    stk3.push("ccc");
    while (stk3.getNum())
    {
        cout << "stk3:" << stk3.pop() << endl;
    }
    cout << "stk3 num:" << stk3.getNum() << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值