首页 > 代码库 > c++模板编程

c++模板编程

#include <cstdio>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <string>

using namespace std;
/**
【1】模板编程,template <typename T>声明模板
*/
template <typename T>
T findmax(T arr[],int len)
{
    T val=arr[0];
    for(int i=1;i<len;i++)
    {
        if(arr[i]>val)val=arr[i];
    }
    return val;
}
/**
【2】类模板
*/
template <int N,typename T>
T* create()
{
    T *str=new T[N];
    return str;
}
///调用 char *p=create<100,char>();
///【3】stack模板例子
template <typename T>
class Stack
{
public:
    Stack(int maxsize)
    {
        m_maxsize=maxsize;
        m_buffer = new T[maxsize];
        m_size = 0;
    }
    ~Stack()
    {
        delete [] m_buffer;
    }
    bool push(const T& value)
    {
        if(m_size>=m_maxsize)return false;
        m_buffer[m_size]=value;
        m_size++;
        return true;
    }
    T pop()
    {
        T last=m_buffer[m_size-1];
        m_size--;
        return last;
    }
    const T& top()
    {
        return m_buffer[m_size-1];
    }
    int _size()
    {
        return m_size;
    }
private:
    T * m_buffer;
    int m_size;
    int m_maxsize;
};
int main()
{
    ///【1】
    puts("1:模板编程");
    int arr[]={1,2,9,6,4};
    double _arr[]={1.5,4.3,5.5,9.8,0.6};
    printf("%d %.2f\n",findmax(arr,5),findmax(_arr,5));
    printf("%d \n",findmax<int>(arr,5));///<int>将模板实例化
    return 0;
}

 

c++模板编程