c++ - Python 的无返回功能模仿 C++

标签 c++ return

我喜欢 Python 中的特性,它可以在找不到正确的返回值时返回 None。例如:

def get(self, key):
    if key in self.db:
        return self.db[key]
    return None

我需要在 C++ 中实现相同的功能。我考虑了一些可能性。

返回true/false,当为true时从引用或指针获取值

bool get(string key, int& result)
{
    if (in(key, db)) {
        result = db[key];
        return true;
    }
    return false;
}

为通知 None case 抛出错误

int get(string key) throw (int)
{
    if (in(key, db)) {
        result = db[key];
        return result;
    }

    throw 0;
}

try {
    ....
}
catch (int n)
{
    cout << "None";
}

使用对

pair<bool, int> getp(int i)
{
    if (...) {
        return pair<bool, int>(true, 10);
    }
    return pair<bool,int>(false, 20);
}

pair<bool, int> res = getp(10);
if (res.first) {
    cout << res.second;
}

在 C++ 中通常使用哪一个?在 C++ 中还有其他方法吗?

最佳答案

正常的 C++ 方法(注意:C++ 不是 Python)是从此类函数返回迭代器,并在找不到项时返回 end()

但是,如果您希望使用非迭代器返回值,请使用 boost::optional 并在返回 Python 的 None< 时返回 boost::none/.

绝对不要使用 throw 除非您希望从不在正常执行期间出现错误情况。

关于c++ - Python 的无返回功能模仿 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098585/

相关文章:

c++ - 带有可变参数模板的成员函数指针

c++ - 有哪些优秀的免费、开源、跨平台游戏引擎?

c++ - 从函数返回多维 vector 供main使用,如何正确使用?

java - 如何打印字符串

javascript - 将函数作为这样的函数的参数在语法上可以接受吗?

javascript - 在异步类型函数中省略返回

c++ - 使用命名空间的区别 (std::vs::std::)

c++ - 我可以使用什么 C++ 库来创建和简化贝塞尔曲线

c++ - 如何检查以前是否已找到最大值位置 C++

java - 将运行时异常封装在retun方法上,或者生成异常方法?