• 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.

  • 相关阅读:
    python处理url中的中文编码,以及其他编码问题
    深度学习与神经网络
    Windows下为64位的python3.4.3安装numpy
    TOP 10开源的推荐系统简介
    遗传算法
    java调用c++生成的动态和静态库时遇到的问题
    java程序(一)----HashMap同时获取键值
    Deep Learning In NLP 神经网络与词向量
    word2vec使用说明
    Spring入门_02_属性注入
  • 原文地址:https://www.cnblogs.com/sssblog/p/11052561.html
Copyright © 2020-2023  润新知