C++模板

作者: 付凯强 | 来源:发表于2021-12-09 01:03 被阅读0次

描述

所谓泛型编程即是以一种独立于特定类型的方式进行编程。而在C++中,模板是泛型编程的基础。
模板大致分为函数模板和类模板。
许多库都使用到了模板,比如向量vector,我们可以定义vector<int>或者vector<string>等。

函数模板

template <typename type> ret-type func-name(parameter list)
{
   // 函数的主体
}

type 是函数所使用的数据类型的占位符名称。这个名称可以在函数定义中使用。

#include<iostream>
using namespace std;

template <typename T>
T const& Max (T const& a,T const& b)
{
    return a < b ? b : a;
}

main()
{
    int a = 5;
    int b =10;
    cout << "Max(a,b) = " << Max(a,b) << endl;
    double f1 = 2.0;
    double f2 = 4.1;
    cout << "Max(f1,f2) = " << Max(f1,f2) << endl;
    string s1 = "Hello";
    string s2 = "World";
    cout << "Max(f1,f2) = " << Max(s1,s2) << endl;
}
Max(a,b) = 10
Max(f1,f2) = 4.1
Max(f1,f2) = World

类模板

template <class type> class class-name {
类的主体
}

type 是占位符类型名称,可以在类被实例化的时候进行指定。

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class Stack
{
    private:
        vector<T> elems;
    public:
        void push (T const&);
        void pop();
        T top() const;
        bool empty() const
        {
            return elems.empty(); 
        } 
};

template <class T>
void Stack<T>::push (T const& elem)
{
    elems.push_back(elem);
}

template <class T>
void Stack<T>::pop()
{
    if (elems.empty())
    {
        throw out_of_range("Stack<>::pop(): empty stack");
    }
    elems.pop_back();
}

template <class T>
T Stack<T>::top() const
{
    if (elems.empty())
    {
        throw out_of_range("Stack<>::top(): empty stack");
    }
    return elems.back();
}

int main()
{
    try{
        Stack<int> intStack;
        Stack<string> stringStack;
        intStack.push(8);
        cout << intStack.top() << endl;
        
        stringStack.push("hello");
        cout << stringStack.top() << endl;
        
        stringStack.pop();
        stringStack.pop();
    }
    catch(exception const& e)
    {
        std::cout <<"Exception: "<< e.what() << endl;
        return -1;
    }
}
8
hello
Exception: Stack<>::pop(): empty stack

相关文章

网友评论

      本文标题:C++模板

      本文链接:https://www.haomeiwen.com/subject/zxmxfrtx.html