在预期返回 Template<T> 值的函数中出现错误时我应该返回什么?

Bre*_*ans 2 c++ templates

我在 OOP 方面还很菜鸟,这是我第一次处理异常和模板,可能是我以错误的方式计划了该函数......但我想知道在这种情况下如果执行出错并且我应该返回什么抛出异常...返回模板的函数中返回什么样的数据错误?抱歉,如果我不够清楚,英语不是我的母语......

template<typename T>
const T& List<T>::Next()
{
    try
    {
        if (_actual->getNext() == NULL)
            throw out_of_range("No next elements, list out of bounds");
        else
        {
            _actual = _actual->getNext();
            _Position++;
            return _actual->getData();
        }
    }
    catch (out_of_range &e)
    {
        cerr << "Error, " << e.what() << endl << "Position: " << _Position << " Elements: " << _Elements << endl;
    }
// <--- what should I return here?? return NULL;? return 0;? return <T> thrash;??
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 5

如果没有什么可返回的,那么就没有什么可返回的。

让异常传播,要么不在这里捕获它cerr,要么在你的语句之后重新抛出它throw

catch (out_of_range &e)
{
    cerr << "Error, " << e.what() << endl
         << "Position: " << _Position
         << " Elements: " << _Elements << endl;
    throw;
}
Run Code Online (Sandbox Code Playgroud)

您的下一个问题将是如何处理调用范围中的异常。:)
但至少你不必再担心返回值了。

  • @black:对,没错。看,当你真正说出你的意思时,比只说“小心”更好! (3认同)