Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ templates problem: convert to null

Tags:

c++

templates

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

like image 281
sorush-r Avatar asked Feb 22 '26 06:02

sorush-r


2 Answers

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.

like image 156
CB Bailey Avatar answered Feb 25 '26 02:02

CB Bailey


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.

like image 39
Oliver Charlesworth Avatar answered Feb 25 '26 01:02

Oliver Charlesworth