zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    java.lang.OutOfMemoryError: Java heap space解决方法
    深入理解SQL的四种连接-左外连接、右外连接、内连接、全连接
    CSS中.和#区别
    斯坦福数据挖掘之LSH的应用
    N个元素的集合划分成互斥的两个子集的数目
    JDBC小结
    初识Java反射机制
    关于Java中重载的若干问题
    吐槽
    Tomcat
  • 原文地址:https://www.cnblogs.com/sssblog/p/11052561.html
Copyright © 2011-2022 走看看