dimanche 26 septembre 2021

c++ function returns two different types

I'm creating a queue template class using C++.

The queue class has multiple function members. One of the functions is called front() to retrieve the first value of queue. Basically, the front() function will first check if the queue is empty or not (using another bool function is_empty()).

If it is empty, the function will throw error message and return 1 to indicate there is an error. If the queue is not empty, it will return the first value, whose type is same as that of data in queue. As you can see, there are two different types of return values. How can I specify those two types together when define the function?

Sample code is below. The return type is T. But the function also returns 1. Is this acceptable in C++? If not, how to modify it? Thanks in advance!

template <class T>
T MyQueue<T>::front() {
    if (! is_empty()) {
        return my_queue[0];
    }
    else {
        cout << "queue is empty!" << endl;
        return 1;
    }
}

Aucun commentaire:

Enregistrer un commentaire