avm
avm

Reputation: 399

What can I return which is valid for every type of <T>?

I have a simple template function implementation for returning the front element from a queue.

template<class T>
T Queue<T>::front(){  //Queue is a typical class implementation of queue
    if(head)          //head points to first element
        return head->data;   //head->data is of type T
    //else return -1  //I want to do something like this 
}

It returns first element if queue is not empty. I know that front() can work without returning anything in case of empty queue but I want to return something so that I can know if the queue is empty (and also to get rid of the compiler warning).

Question- What can I return when queue is empty? Since its return type is T so I can't return a predefined value(like bool or int) for all types of T.

Upvotes: 0

Views: 82

Answers (2)

eerorika
eerorika

Reputation: 238441

What can I return which is valid for every type of <T>?

One typical design, used in the C++ standard library is to return an iterator. This design is used for example in find.

Another design is to return a reference. This is used with front and at and subscript operator for example.

Question- What can I return when queue is empty?

In the iterator design, it is typical to return an iterator to one past the last element.

In the reference case, you couldn't return anything because there is nothing to refer to. In this design, there are several alternatives, some used by the standard library in different contexts:

  • Document a pre-condition for the function that it may not be called when the container is empty. If caller violates the pre-condition, then the behaviur of the program will be undefined. This is the approach that standard library uses with front and the subscript operator.
  • Treat such case as an error. There are many ways to design error handling in C++, but a typical choice is throwing an exception. This is what the standard library does in the case of at.

Another design, not used so much in the standard library is to return a std::optional<T>, and to return std::nullopt in the empty case.


I know that front() can work without returning anything

This is a potential misuderstanding. Instead of returning, you can for example throw. Or you can end the process. But letting the execution flow out of the function without return or throw will result in undefined behaviour.

Upvotes: 3

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

You can:

  • Return a pointer that's conditionally null.
  • Throw an exception.
  • Document that it's undefined behavior.

Depends on what conventions your project already has. Another thing is that you're returning the element by value, which is probably not the right call.

Upvotes: 2

Related Questions