Search code examples
c++templateserror-handlingstackapi-design

What to do in a (templated) stack pop method when the stack is empty?


I have written a templatized container class that takes type and template of template parameter.

template<class type, template<typename...> class Seq>
class stack1
{
private:
    int count;
    int size;
    Seq<type> st;
    //Seq<string> str;

public:
    stack1(size_t size):size(100), count(-1){ }
    void push(type elem);
    type pop();

};


template<class type, template<typename...> class Seq>
type stack1<type, Seq>::pop()
{
    if (count < 0)
    {
        cout << "stack1 is empty," << endl;
        /*How to handle this condition.*/

    }
    else
    {
        type elem; 
        elem = st.back();
        st.pop_back();
        count--;
        return elem;
    }
}

my question is , in the pop function how should I handle the error scenario when the container object is empty. I want to return some default value in that case, e.g. 0/-1 if the container is int or ""/null if it is string or 0.0 in case it is float... something like that.


Solution

  • @RSahu's suggestion is a fine thing to have.

    An alternative could be changing the signature of the pop() function from:

    type pop();
    

    to

    std::optional<type> pop();
    

    and returning std::nullopt if the stack is empty, or a wrapped value in the usual case:

    if (count < 0) {
        return std::nullopt;
    }
    

    Note that std::optional is introduced in the C++17 language standard; in C++14 you have it as std::experimental::optional, or you can use boost::optional for C++11 and earlier.

    PS: It's a bad idea to have count be -1 when the element count is actually 0 - very confusing!