• 模板笔记4 非类型模板参数


    #include <string>
    #include <iostream>
    #include <stdexcept>

    template<typename T, int MAXSIZE>
    //template<typename T = int, int MAXSIZE = 100>//可以指定默认值!!!
    class Stack{
    private:
    T elems[MAXSIZE];
    int numElems;
    public:
    Stack();
    void push(T const&);
    void pop();
    T top() const;
    bool empty() const{
    return numElems == 0;
    }
    bool full() const {
    return numElems == MAXSIZE;
    }
    };

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

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

    --numElems;
    }


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

    int main()
    {
    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;
    }
    }

    非类型模板参数的限制:可以时常整数(包括枚举值)和指向外部链接对象的指针。

    不允许是浮点数,类对象和内部链接对象。

    错误举例:

    template<char const *name>

    class Myclass{

      ...;

    };

    char const* s = 'hello";//错误不能使用全局指针作为模板参数

    Myclass<s>  x;//错误,s是指向内部链接对象的指针

  • 相关阅读:
    扫描线算法
    [Baltic 2001]Mars Maps
    Lost Cow
    李超线段树
    多种方法求解Pku3468 A Simple Problem with Integers
    陈老师的福利
    leetcode 673. 最长递增子序列的个数
    #10043.「一本通 2.2 例 1」剪花布条
    PTA7-1
    6-1 实验三哈夫曼树 (15分)
  • 原文地址:https://www.cnblogs.com/xpylovely/p/12482571.html
Copyright © 2020-2023  润新知