Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's None return feature mimicking in C++

Tags:

c++

return

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.

Return true/false, when true get the value from reference or pointer

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

Throw an error for notifying 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";
}

Use pair

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++?

like image 862
prosseek Avatar asked Jun 13 '13 22:06

prosseek


People also ask

What is the equivalent of none 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.

What is C library in Python?

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.


1 Answers

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.

like image 142
Mark B Avatar answered Sep 30 '22 07:09

Mark B