I wrote a generic stack for practicing. The question is about what type I should return in case stack empty. The first thing comes to my mind is returning -1 :
U pop_back()
{
if (m_pos <= 0)
{
std::cout << "Stack <pop_back> No element in stack will return default " << std::endl;
return -1;
}
return m_data[m_pos--];
}
But this will limit my generic container to integer types. And also -1 can be a data for integer types instead of error. Other options in my mind handle error with exceptions or default ctors .
Please advice me the best way of returning error in those kind of situations.
Whole code can be seen below.
template <typename U, std::size_t n>
class Stack
{
public:
Stack()
{
m_pos = -1;
}
U pop_back()
{
if (m_pos <= 0)
{
std::cout << "Stack <pop_back> No element in stack will return default " << std::endl;
return -1;
}
return m_data[m_pos--];
}
void push_back(U val)
{
if (m_pos >= m_data.size())
{
std::cout << " Stack <push_back> Capasity is full won't add more" << std::endl;
return;
}
m_data[++m_pos] = val;
}
private:
int m_pos;
std::array<U, n> m_data;
};