Using a template several times

  c++

I was trying to implement max-queue
But a more general version with arbitrary Associative function and arbitrary data type.I did the following for the max_stack part:

template<typename T,class F=function<T(const T&,const T&)> >
class Stack{
    F func;
    stack<pair<T,T> > st;
public:
    Stack(F f):func(f){};
    bool empty(){
        return st.empty();
    }
    int size(){
        return st.size();
    }
    void push(T nw){
        if(empty()){
            st.emplace(nw,nw);
            return;
        }
        T prev=st.top().second;
        prev=func(prev,nw);
        st.emplace(nw,prev);
    }
    T pop(){
        return st.pop();
    }
    T getval(){
        return st.top().second;
    }
};

The program worked well and the test was sucessful but then initializing two max_stacks for a max_queue caused some problems I implemented it as follows:

class Queue{
    F func;
    Stack<T> right;
    Stack<T> left;
public:
    explicit Queue(F f): func(f){
        right(f);
        left(f);
    }
    void push(T nw){
        right.push(nw);
    }
    void pop(){
        if(left.empty()){
            while(!right.empty()){
                left.push(right.pop());
            }
        }
        assert(!left.empty());
        left.pop();
    }
    T getval(){
        return func(right.getval(),left.getval());
    }
};

my editor didn’t give me any errors until I tried to use it.I initialized the queue as follows:

Queue<int> qp([&](int a,int b){
        return min(a,b);
    });

Then my editor gives the error: "Constructor for ‘Queue<int, std::function<int (const int &, const int &)>>’ must explicitly initialize the member ‘left’ which does not have a default constructor"

And the similar for the left stack.It seems that The problmes is about the template types.How can I fix that?

Source: Windows Questions C++

LEAVE A COMMENT