简体   繁体   English

在错误情况下应该返回模板的函数应该返回什么 <T> 值?

[英]What should I return in an error case in a function expected to return a Template<T> value?

I'm quite noob yet in OOP and is my first time handling exceptions and Templates, may be I planned the function in a wrong way... But I would like to know what should I return in this case if the execution goes wrong and the exception is thrown.... what kind of data error return in a function returning a Template? 我在OOP中还算是新手,这是我第一次处理异常和模板,可能是我以错误的方式计划了函数……但是我想知道如果执行出错并在这种情况下应该返回什么?引发异常。...返回模板的函数中返回哪种数据错误? Sorry if I am not clear enough, english is not my mothertongue... 抱歉,如果我不太清楚,英语不是我的母语。

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

If there's nothing to return then there's nothing to return. 如果没有退货,那就没有退货。

Let the exception propagate, either by not catching it here , or by re-throwing it after your cerr statement with the throw statement: 让异常传播,方法是不在此处捕获它 ,或者在您的cerr语句之后使用throw语句将其重新throw

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

Your next question will be how to handle the exception in the calling scope. 您的下一个问题将是如何在调用范围内处理异常。 :) :)
But at least you won't have to worry about return values any more. 但是至少您不必再担心返回值了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 函数返回一个指向对象的指针,在这种情况下我该返回什么? - function returns a pointer to an object, what should I return in this case? 当函数没有返回值时,返回类型应该是什么? - What should the return type be when the function might not have a value to return? 从函数模板错误返回修改后的值 - return modified value from a function template error 下面的多参数 function 模板的返回类型应该是什么? - What should be the return type of the following function template with multiple parameters? .cpp 文件中纯虚函数的正确返回值应该是多少? - What should be the correct return value of a pure virtual function in .cpp file? 功能应该回归价值问题 - Function Should Return Value Question 为什么从模板 function 返回的值上的 decltype 返回 T - Why does decltype on value returned from template function return T 如果不满足条件,我应该在成员函数中返回什么? - What should I return in a member function if a condition is not met? 为什么我不能从这个模板函数返回引用? - Why can't I return a reference from this template function? 我想在C ++中为map &lt;&gt;的给定键返回一个VALUE。 如果map &lt;&gt;中不存在KEY,返回什么? - I want to return a VALUE for given KEY for map<> in c++. What to return in case KEY is not present in map<>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM