0

Templates are nice for similar algorithms of different data types. Say I make a template stack of a basic data type...

Stack<int> stck(10);
stck.Push(5);

I'd pop it...

int x = stck.Pop();

x would be 5. If I call pop again, there are no items, so I have the method just return 0 for null. It could be something else, but whatever.

But now, if I change the template type to a compound variable (a structure type - say, RECT), and the stack is empty, it can't return 0. It expects a RECT type, but I don't have any left. How do I make this work for basic data types and compound variables? Exceptions?

  • 1
    Add an Empty() function so the user has some chance of avoiding this issue – James Apr 18 '14 at 21:37
4

3 options

make popping en emtpy stack undefined and don't worry about it

throw an exception

return default constructed T() (which happens to be 0 for the numeric types)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.