boost::optional can be used for optional return values.

1. optional return values with boost::optional

#include <boost/optional.hpp>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>

using boost::optional;

optional<int> get_even_random_number() {
  int i = std::rand();
  return (i % 2 == 0) ? i : optional<int>();
}

int main() {
  std::srand(static_cast<unsigned int>(std::time(0)));
  optional<int> i = get_even_random_number();
  if (i) {
    std::cout << std::sqrt(static_cast<float>(*i)) << std::endl;
  }
  return 0;
}

boost::optional is a template that must be instantiated with the actual type of the return value.

If get_even_random_number() generates an even random number, the value is returned directly, automatically wrapped in an object of type boost::optional<int>, because boost::optional provides a non-exclusive constructor. If get_even_random_number() does not  generate an even random number, an empty object of type boost::optional<int> is returned. The return value is created with a call to the default constructor.

main() checks whether i is empty. If it isn't empty, the number stored in i is accessed with operator*.

2. other useful member functions of boost::optional

#include <boost/optional.hpp>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>

using boost::optional;

optional<int> get_even_random_number() {
  int i = std::rand();
  return optional<int>(i % 2 == 0, i);
}

int main() {
  std::srand(static_cast<unsigned int>(std::time(0)));
  optional<int> i = get_even_random_number();
  if (i.is_initialized()) {
    std::cout << std::sqrt(static_cast<float>(i.get())) << std::endl;
  }
  return 0;
}

This class provides a special constructor that takes a condition as the first parameter. If the condition is true, an object of type boost::optional is initialized with the second parameter. If the condition is false, an empty object of type boost::optional is created. With is_initialized() you can check whether an object of type boost::optional is not empty.

相关文章:

  • 2021-10-29
  • 2021-12-01
  • 2021-07-18
  • 2022-02-01
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-07
  • 2021-06-06
  • 2022-02-06
相关资源
相似解决方案