Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost::optional<T> to return NULL in C++?

Tags:

c++

boost

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.

like image 979
czchlong Avatar asked Oct 27 '11 14:10

czchlong


People also ask

What is boost :: optional?

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.

How do you assign a value to boost optional?

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();

What does return null mean in C?

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 .


2 Answers

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 */ }
like image 132
rerun Avatar answered Nov 07 '22 18:11

rerun


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;.

like image 29
Mark B Avatar answered Nov 07 '22 18:11

Mark B