I have a function that needs to return NULL in some cases and there is another function that needs to test for the return value of this function. I am aware of boost::optional but am not sure how to use the syntax.
Below would be a simple example of said usage:
int funct1(const string& key) {
// use iterator to look for key in a map
if(iterator == map.end()) {
return NULL // need help here!
else
return it->second;
}
void funct2(string key) {
if(funct1(key) == NULL) { // <-- need help here!
// do something
} else {
// do something else
}
Can someone please help with the syntax?
Thanks.
boost::optional<T> provides an alternative way to support the null data condition and as such relieves the user from necessity to handle separate indicator values. The boost::optional<T> objects can be used everywhere where the regular user provided values are expected.
A default-constructed boost::optional is empty - it does not contain a value, so you can't call get() on it. You have to initialise it with a valid value: boost::optional<myClass> value = myClass();
return is used to "break" out from a function that has no return value, i.e. a return type of void . return NULL returns the value NULL , and the return type of the function it's found in must be compatible with NULL .
It stays in the "NULL
" state until you set it. You can use this idiom:
optional<int> funct1(const string& key) {
// use iterator to look for key in a map
optional<int> ret;
if (iterator != map.end())
{
ret = it->second;
}
return ret;
}
Then:
if (!funct1(key)) { /* no value */ }
Let me mention a few things before I get to the question.
If the string should always be found (programmer error if it's not) you should probably throw if it can't be instead of using an optional. You may even want to try/catch/throw even if it's user input.
If your class mimics container like semantics, you should consider using an end
sentinel to indicate that it wasn't found, not null.
If however returning a null representation is what you're after, your function return type would be boost::optional<int>
and the null return would be return boost::none;
.
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