简体   繁体   中英

How to return a generic value in a function

I am trying to implement generic STACK using vector where STACK can be of type int , double or string etc

I am facing issue with pop method where I'm supposed to return a value which is of type Object . If stack is empty I'm returning -1 obviously which won't work if STACK is of type string . Is there a way where I can deal with this situation?

#include <bits/stdc++.h>

using namespace std;


template <typename Object>
class Stack{
    private:
        int top;
        int maxSize;
        vector<Object> object;

    public:
        explicit Stack(const int size) : maxSize{size}, top{-1} {
            object.reserve(maxSize);

        }

        Object pop(){
            Object val = -1;
            if(top == -1){
                cout << "Stack Underflow" << endl;
                return val;
            } else{
                val = object[top];
                // object.erase(object.begin() + top);
                // object[top] = 0;
                --top;
                return val;
            }
        }
 };

Edit:

What will be a better choice here? From the comments it seems obvious returning -1 is not feasible. How can I make it generic where empty stack will return an value which is generic?

How can I make it generic where empty stack will return an value which is generic?

To my knowledge: No you can't, at least not in the stack design you described where pop() will always return a value of Object and that must be also a generic value for all types. That's because there is no generic magic value all types can be set to.

You only have some alternatives: Throw an exception in pop() if your stack is empty like

#include <stdexcept>
...
Object pop(){
    if(top == -1){
        throw std::out_of_range("pop:: Stack is empty");

or change the signature of pop returning something like a std::optional or std::variant .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM