C++(四十二) — 函数模板多态

 1、函数模板(参数多态)

  相当于一个函数发生器,参数多态,可以重载。

  普通函数和模板函数的本质区别

  1. 普通函数的调用,可以进行隐式的类型转换;
  2. 函数模板的调用,使用类型参数化,严格按照类型进行匹配,不会进行类型的自动转换;

   一个函数模板可以取代许多具体的函数定义,可以大大减少编程工作量。

#include <iostream>
#include <typeinfo>
using namespace std;

template <typename P> //函数模板
void ArrayInput(P array, int num)
{
    cout << "输入" << num << "" << typeid(P).name()
        << "\b" << "型数据" << endl;
    for (int j = 0; j < num; j++)
        cin >> array[j];
}
void main()
{
    int number;
    float floatArray[4];
    int intArray[3];
    number = sizeof(floatArray) / sizeof(float);
    ArrayInput(floatArray, number);
    number = sizeof(intArray) / sizeof(int);
    ArrayInput(intArray, number);
    system("pause");
}

 

2、类模板

   使用类模板来定义栈类,进栈、出栈。

#include <iostream>
#include <typeinfo>
using namespace std;

template <class T,int i> //函数模板
class MyStack
{
private:
    //栈空间:Buffer[0]~Buffer[i-1],Buffer[i]表示栈底
    T Buffer[i + 1];
    int size;
    int top;
public:
    MyStack(T zero)
    {
        size = i;
        top = i;
        for (int j = 0; j <= i; j++)  //初始化缓冲区
        {
            Buffer[j] = zero;
        }
    }
    void push(const T item);
    T pop();
};

template <class T,int i>  // 模板类成员函数的定义
void MyStack<T, i>::push(const T item)
{
    if (top > 0)
        Buffer[--top] = item;
    else
        cout << "栈溢出" << endl;
}

template <class T,int i>
T MyStack<T, i>::pop()
{
    T temp;
    if (top < size)
        temp = Buffer[top++];
    else
    {
        temp = Buffer[top];
        cout << "栈已空" << endl;
    }
    return temp;
}

void main()
{
    MyStack<int, 5> S1(0);
    S1.push(4);
    cout << S1.pop() << endl;
    MyStack<char*, 5> S2("empty");
    S2.push("china");
    cout << S2.pop() << endl;
    cout << S2.pop() << endl;
    system("pause");
}

 

posted @ 2019-06-03 10:51  深度机器学习  阅读(1076)  评论(0编辑  收藏  举报