• 模板笔记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();
    }

  • 相关阅读:
    npm uninstall g 和 D什么区别
    js filter 去除对象中重复元素
    vueloader 安装指定版本 与 卸载
    [六、常用控件]9UIDatePicker日期时间选择器
    [六、常用控件]13在MKMapView地图上显示提示框
    [六、常用控件]12为MKMapView指定地理坐标
    [六、常用控件]6UITextField控件的使用
    [六、常用控件]8动作表样式警告窗口的使用
    [六、常用控件]5UISwitch开关控件的使用
    [六、常用控件]2UIButton图片按钮的使用
  • 原文地址:https://www.cnblogs.com/xpylovely/p/12517076.html
Copyright © 2020-2023  润新知