非类型模板参数

第四章:

一、非类型的类模板参数

template不仅可以使用参数typename,一般的参数也是可以用的。这里定义了最大数组。

#pragma once
#include <stdexcept>


template<typename T, int MAXSIZE>
class Stack
{
private:
    T elems[MAXSIZE];
    int numElems;
public:
    Stack();
    void push(T const &elem);
    void pop();
    T top() const;
    bool empty() const {
        return numElems == 0;
    }
    bool full() const {
        return numElems == MAXSIZE;
    }
};

template<typename T, int MAXSIZE>
inline Stack<T, MAXSIZE>::Stack()
    : numElems(0)
{
}

template<typename T, int MAXSIZE>
inline void Stack<T, MAXSIZE>::push(T const & elem)
{
    if (numElems == MAXSIZE) {
        throw std::out_of_range("Stack<>::push(): stack is full");
    }
    elems[numElems] = elem;
    ++numElems;
}

template<typename T, int MAXSIZE>
inline void Stack<T, MAXSIZE>::pop()
{
    if (numElems <= 0) {
        throw std::out_of_range("Stack<>::pop() empty stack");
    }
    --numElems;
}

template<typename T, int MAXSIZE>
inline T Stack<T, MAXSIZE>::top() const
{
    if (numElems < 0) {
        throw std::out_of_range("Stack<>::top() stack is empty");
    }
    return elems[numElems - 1];
}

测试函数:

#include <iostream>
#include <string>
#include <cstdlib>
#include "stack4.hpp"

int main()
{
    std::cout << "Hello World!\n";
    try {
        Stack<int, 20> int20Stack;
        Stack<int, 40> int40Stack;
        Stack<std::string, 40> stringStack;

        int20Stack.push(7);
        std::cout << int20Stack.top() << std::endl;
        int20Stack.pop();

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

 

posted @ 2020-05-27 13:40  习惯就好233  阅读(478)  评论(0编辑  收藏  举报