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
Tby 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 aT*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 ofIsEmptyto avoid receiving the exception which becomes the equivalent of an assert.