I have a Stack container class and I want to create instances of various types of Stacks. so I do this:
template <typename T>
class MyStack
{
.
.
T Pop()
{
if(!IsEmpty())
{
return data[top--];
}
else
{
return NULL; // I got error here
}
.
.
}
When I try to use Stack like this:
MyStack<GraphNode> blacks;
GraphNode t = blacks.Pop();
I got this error:
conversion from ‘int’ to non-scalar type ‘GraphNode’ requested
But when I use a pointer type like Stack<GraphNode*> there is no problem. I know that NULL is 0 and I understand why error occurs... What is the elegant way to tell program that there is no data to return without changing the code? should I add something like an implicit type conversion operator to class? how?
NOTE: I'm not using STL
By returning a T by value, the contract of your function is that you will return a value. The two alternatives are to change the contract of your function (e.g. return a T* instead) or to fail to return by throwing an exception.
Personally, I think that it is acceptable and appropriate to throw an exception in this case. Returning a pointer, or talking a reference to overwrite and returning a boolean success value are both less clean solutions.
Especially if you provide a public IsEmpty() method there is no reason to choose a less clean solution. Clients that don't want to handle exceptions can make use of IsEmpty to avoid receiving the exception which becomes the equivalent of an assert.
The STL std::stack splits this functionality into top(), which returns a reference to the last element, and pop(). The behaviour is simply undefined if you use either of these and the stack is already empty (i.e. if empty() == true). This doesn't sound like a bad approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With