Reputation: 399
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
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:
front
and the subscript operator.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
Reputation: 29985
You can:
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