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.

  • 相关阅读:
    iOS-runtime-根据协议名调某一个类有与协议里面放的相同的方法
    Mac下显示隐藏文件
    OC开发_整理笔记——多线程之GCD
    兵器簿之cocoaPods的安装和使用
    手写代码UI,xib和StoryBoard间的的优劣比较
    OC开发_Storyboard——MapKit
    smartFloat
    固定浮动侧边栏(SmartFloat)
    一个模拟时钟的时间选择器 ClockPicker
    分布式事务TransactionScope
  • 原文地址:https://www.cnblogs.com/sssblog/p/11052561.html
Copyright © 2011-2022 走看看