如何使用boost :: optional <T>在C++中返回NULL?

czc*_*ong 9 c++ boost

我有一个函数需要在某些情况下返回NULL,还有另一个函数需要测试此函数的返回值.我知道boost :: optional但不知道如何使用语法.

以下是所述用法的简单示例:

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
  }
Run Code Online (Sandbox Code Playgroud)

有人可以帮助解决语法问题吗?

谢谢.

rer*_*run 14

NULL您设置之前,它一直处于" "状态.你可以用这个成语:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后:

if (!funct1(key)) { /* no value */ }
Run Code Online (Sandbox Code Playgroud)