C++模板

模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。

模板是创建泛型或函数的蓝图或公式。库容量,比如迭代器和算法,都是泛型编程的例子。

每个容器都有一个单一的定义,比如向量,我们可以定义许多不同类型的向量。比如vector<int> 或vector<string>

 

函数模板

模板函数定义的一般形式如下所示:

template<class type> ret-type func-name(paramrter list)
{
    //函数主体
}

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

下面是函数模板的实例,返回两个数的最大值:

/***
template.cpp
***/
#include<iostream>
#include<string>

using namespace std;

template<typename T>
inline T const& Max(T const&a, T const& b)
{
    return a < b ? a : b;
}
int main()
{
    int i = 39;
    int j = 20;

    cout << "Max(i,j): " << Max(i,j) << endl;

    double f1 = 13.5;
    double f2 = 20.7;
    cout << "Max(f1,f2) : " << Max(f1,f2) << endl;

    string s1 = "hello";
    string s2 = "world";
    cout << "Max(s1,s2): " << Max(s1,s2) << endl;

    return 0;
    
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190816$ g++ template.cpp -o template

exbot@ubuntu:~/wangqinghe/C++/20190816$ ./template

Max(i,j): 20

Max(f1,f2) : 13.5

Max(s1,s2): hello

类模板:

正如我们定义函数模板一样,我们也可定义类模板,泛类声明的一般形式如下所示:

template <class type> class class-name
{
    …
}

在这里,type是占位符类型名称,可以在类被实例化的时候进行指定,可以使用一个逗号分隔的列表来定义多个泛型数据类型。

下面的实例定义了类的Stack<>,并实现了泛型方法来对元素进行入栈出栈操作:

/***
stack.cpp
***/
#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<>::pop():empty stack");
    }
    return elems.back();
}

int main()
{
    try
    {
        Stack<int> intStack;
        Stack<string> stringStack;

        intStack.push(7);
        cout << intStack.top() << endl;

        stringStack.push("hello");
        cout << stringStack.top() << endl;
        stringStack.pop();
        stringStack.pop();
    }
    catch(exception const& ex)
    {
        cerr << "Exception: " << ex.what() << endl;
        return -1;
    }
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190816$ g++ stack.cpp -o stack

exbot@ubuntu:~/wangqinghe/C++/20190816$ ./stack

7

hello

Exception: Stack<>::pop():empty stack

原文地址:https://www.cnblogs.com/wanghao-boke/p/11362801.html