Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template return when Element is a struct

Tags:

c++

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

like image 408
Charlotte45 Avatar asked Jan 17 '26 06:01

Charlotte45


2 Answers

The solution depends on you:

  1. Have undefined behaviour if a function is called on an empty container. You should document these cases clearly. In such a case the user would have to check if the call to a function would be valid via for example an empty method. This is the case for std::vector::front.
  2. Throw an exception like std::vector::at does.
  3. Return boost::optional as descriped in the other answer
  4. Return a pointer or an iterator like suggested in the comments
  5. Since you are not returning references to the elements you could also return a default constructed object of type T, 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.

like image 90
mfuchs Avatar answered Jan 19 '26 20:01

mfuchs


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.

like image 40
Ami Tavory Avatar answered Jan 19 '26 19:01

Ami Tavory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!