Home > Enterprise >  c function returns two different types
c function returns two different types

Time:09-27

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;
    }
}

CodePudding user response:

One option is to use std::optional:

template <class T>
std::optional<T> MyQueue<T>::front() {
    // You should remove the object from the queue here too:
    if (!is_empty()) return my_queue[0];
    return {};
}

You can then use it like so:

    if(auto opt = queue_instance.front(); opt) {
        auto value = std::move(opt).value();
        std::cout << "got :" << value << '\n';
    } else {
        std::cout << "no value right now\n";
    }

CodePudding user response:

I would suggest returning T* as a pointer. If the queue is empty, then return null.

template <class T>
T* MyQueue<T>::front() {
    return is_empty() ? nullptr : &my_queue[0];
}

if (auto obj = queue.front()) {
    obj->...
}
  • Related