I like the feature in Python that can return None when it doesn't find the correct return value. For example:
def get(self, key):
if key in self.db:
return self.db[key]
return None
I need to implement the same feature in C++. I think about some possibilities.
bool get(string key, int& result)
{
if (in(key, db)) {
result = db[key];
return true;
}
return false;
}
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;
}
Which one is normally used in C++? Are there any other ways to do it in C++?
bitset none() in C++ STL bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set.
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
The normal C++ way to do this (note: C++ is not Python) is to return iterators from such functions and return end()
when the item can't be found.
If you wish to use non-iterator return values however, use boost::optional
and return boost::none
when you would return Python's None
.
Definitely don't use throw
unless you expect to never have the error case during normal execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With