mercredi 27 janvier 2016

How to return an optional

Suppose I have a function which finds and returns the minimum element of a vector. If the vector is empty, it should return an empty optional object. Is there a way for me to use the optional<T> constructor to avoid using either an if statement or the ternary operator?

With if statement:

optional<Foo> GetMinElement(vector<Foo> foos) {
  vector<Foo>::iterator min_foo = std::min_element(foos.begin(), foos.end());
  bool found_min_element = (min_foo != foos.end());
  if (found_min_element) {
    return *min_foo;
  } else {
    return nullopt;
  }
}

With ternary operator:

optional<Foo> GetMinElement(vector<Foo> foos) {
  vector<Foo>::iterator min_foo = std::min_element(foos.begin(), foos.end());
  bool found_min_element = (min_foo != foos.end());
  return found_min_element ? optional<Foo>(*min_foo) : optional<Foo>(nullopt);
}

Naively, I'd just like to be able to pass the output of an stl algorithm to the optional<T> constructor and have it handle the logic of checking for a null pointer. Is there some idiom for this?

Aucun commentaire:

Enregistrer un commentaire