• 模板笔记5 模板的模板参数


    #include <iostream>
    #include <deque>
    #include <stdexcept>
    #include <memory>
    #include <vector>
    template<typename T, template<typename ELEM, typename = std::allocator<ELEM>> class CONT = std::deque>
    class Stack{
    private:
    CONT<T> elems;
    public:
    void push(T const&);
    void pop();
    T top() const;
    bool empty() const{
    return elems.empty();
    }
    template<typename T2, template<typename ELEM2, typename = std::allocator<ELEM2>> class CONT2>
    Stack<T, CONT>& operator=(Stack<T2, CONT2> const&);
    };

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

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

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

    template<typename T, template<typename,typename> class CONT>
    template<typename T2, template<typename, typename> class CONT2>
    Stack<T,CONT>& Stack<T,CONT>::operator=(Stack<T2,CONT2> const& op2)
    {
    if ((void *)this == (void *)&op2) {
    return *this;
    }
    Stack<T2,CONT2> tmp(op2);
    elems.clear();
    while (!tmp.empty()) {
    elems.push_front(tmp.top());
    tmp.pop();
    }
    return *this;
    }

    int main()
    {
    try{
    Stack<int> intStack;
    Stack<float> floatStack;

    intStack.push(42);
    intStack.push(7);

    floatStack.push(7.7);

    floatStack = intStack;

    std::cout << floatStack.top() << std::endl;
    floatStack.pop();
    std::cout << floatStack.top() << std::endl;
    floatStack.pop();
    std::cout << floatStack.top() << std::endl;
    floatStack.pop();
    }
    catch (std::exception const& ex)
    {
    std::cerr << "Exception: " << ex.what() << std::endl;
    }
    Stack<int, std::vector> vStack;

    vStack.push(42);
    vStack.push(7);
    std::cout << vStack.top() << std::endl;
    vStack.pop();
    }

  • 相关阅读:
    第二节:Java环境变量配置
    第一节:VS充当IIS的配置步骤(VS2017和VS2019)
    .Net进阶系列(21)-跨域请求
    02-Unity深入浅出(二)
    第十五节:Expression表达式目录树(与委托的区别、自行拼接、总结几类实例间的拷贝)
    01-Unity深入浅出(一)
    第十二节:SQLServer存储过程详解及EFCore调用
    Android 组件系列-----Activity的传值和回传值
    Access大数据高效分页语句
    C#清除HTML样式
  • 原文地址:https://www.cnblogs.com/xpylovely/p/12517076.html
Copyright © 2020-2023  润新知