So as the title states I have this problem. I'm implementing a Doubly Linked List as a template and on some of the functions like
Element getFirst();
Element getLast();
Element getPosition(int position);
They are supposed to return an element of type Element. The problem is, what if the list is empty? What do I return then? I can't return 0 or some integer because what if my Element is a struct. It will crash later in the code. What should my return be then? I tried creating an empty variable of type Element and sending it but this doesn't work either. Any ideas?
I can provide any piece of code you need, or information. Just ask
The solution depends on you:
empty method. This is the case for std::vector::front.std::vector::at does.boost::optional as descriped in the other answerT, which ideally would have a way to check that it is invalid. Similar to what QHash::value does.In either case you have to do checks somewhere in your code.
There are several options:
Provide a query method to see if the object can support the op (e.g., empty).
Return something that can signify "empty". E.g., you can return a (const) pointer, or optional<Element>.
A different approach, which would work but should be avoided, is to throw an exception.
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