boost optional


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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM