c++函数returns两种不同的类型
c++ function returns two different types
我正在使用 C++ 创建队列模板 class。
队列class有多个函数成员。其中一个函数称为 front() 以检索队列的第一个值。基本上,front() 函数将首先检查队列是否为空(使用另一个 bool 函数 is_empty()).
如果为空,函数会抛出错误信息,return1表示有错误。如果队列不为空,则取return第一个值,其类型与队列中的数据相同。如您所见,有两种不同类型的 return 值。如何在定义函数时同时指定这两种类型?
示例代码如下。 return类型是T。但是函数也是returns 1.这在C++中可以接受吗?如果不是,如何修改?提前致谢!
template <class T>
T MyQueue<T>::front() {
if (! is_empty()) {
return my_queue[0];
}
else {
cout << "queue is empty!" << endl;
return 1;
}
}
一种选择是使用 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 {};
}
然后您可以像这样使用它:
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";
}
我建议 returning T*
作为指针。如果队列为空,则 return null.
template <class T>
T* MyQueue<T>::front() {
return is_empty() ? nullptr : &my_queue[0];
}
if (auto obj = queue.front()) {
obj->...
}
我正在使用 C++ 创建队列模板 class。
队列class有多个函数成员。其中一个函数称为 front() 以检索队列的第一个值。基本上,front() 函数将首先检查队列是否为空(使用另一个 bool 函数 is_empty()).
如果为空,函数会抛出错误信息,return1表示有错误。如果队列不为空,则取return第一个值,其类型与队列中的数据相同。如您所见,有两种不同类型的 return 值。如何在定义函数时同时指定这两种类型?
示例代码如下。 return类型是T。但是函数也是returns 1.这在C++中可以接受吗?如果不是,如何修改?提前致谢!
template <class T>
T MyQueue<T>::front() {
if (! is_empty()) {
return my_queue[0];
}
else {
cout << "queue is empty!" << endl;
return 1;
}
}
一种选择是使用 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 {};
}
然后您可以像这样使用它:
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";
}
我建议 returning T*
作为指针。如果队列为空,则 return null.
template <class T>
T* MyQueue<T>::front() {
return is_empty() ? nullptr : &my_queue[0];
}
if (auto obj = queue.front()) {
obj->...
}