我喜欢 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/