模板类使用示例(一)

以下是一个Stack的模板实现类,注意GCC不支持将模板类的声明和定义分开放(普通类支持):

TestCC.h文件的内容:

#ifndef TESTCC_H
#define TESTCC_H

#include <iostream>
#include <vector>
#include <stdexcept>

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

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

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

    elems.pop_back();
}

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

    return elems.back();
}

#endif // TESTCC_H

测试文件main.cpp:

#include <iostream>
#include <string>
#include <cstdlib>
#include "TestCC.h"

using namespace std;

int main()
{
    try
    {
        Stack<int> intStack;
        intStack.push(7);
        cout << intStack.top() << endl;

        Stack<string> stringStack;
        stringStack.push("hello");
        cout << stringStack.top() << endl;
        stringStack.pop();
        stringStack.pop();
    }
    catch (std::exception const& ex)
    {
        cerr << "Exception: " << ex.what() << endl;
        return EXIT_FAILURE;// In stdlib.h
    }
}

结果:

原文地址:https://www.cnblogs.com/AmitX-moten/p/4445766.html