C++点滴--boost optional 和 variant

这篇博客记录了C++中使用Boost库的optional和variant两个特性的简单示例,旨在个人学习和备忘。
摘要由CSDN通过智能技术生成

只是一点例子,没有什么解释;主要是给自己看,作为一个笔记而已。

boost::optional例子:

#include <boost/optional.hpp>
#include <iostream>


class Inner
{
  private:
    int v;

  public:
    Inner(int _v) : v(_v)
    {}

    Inner(const Inner& other) : v(other.v)
    {
      std::cout << "Inner(const Inner& other)" << std::endl;
    }

    Inner& operator=(const Inner& other)
    {
      this->v = other.v;
      std::cout << "Inner& operator=(const Inner& other)" << std::endl;
      return *this;
    }

    bool operator==(const Inner& other)
    {
      std::cout << "bool operator==(const Inner& other)" << std::endl;
      return this->v == other.v;
    }

    friend std::ostream& operator<<(std::ostream& out, const Inner& inner)
    {
      out<<"Inner("<<inner.v<<")";
      return out;
    }

    int get_v()
    {
      return v;
    }

    void set_v(int _v)
    {
      v = _v;
    }
};

int main()
{
  boost::optional<Inner> option1;
  assert(!option1);

  boost::optional<Inner> option2(boost::none);
  assert(!option2);

  Inner inner3(3);

  //the following two statements are equal to each other;
  boost::optional<Inner> option3(inner3);  // output: Inner(const Inner& other)  -- copy the object;
  boost::optional<Inner> option4 = inner3; // output: Inner(const Inner& other)  -- copy the object;

  assert(*option3 == *option4);  // output: bool operator==(const Inner& other)  -- behaves like a pointer;

  //optional behaves like a pointer, but it holds a copy of the object instead of the pointer of the object;
  std::cout << "option3 = " << option3->get_v() << std::endl; // output: option3 = 3
  option3->set_v(8);
  std::cout << "option3 = " << option3->get_v() << std::endl; // output: option3 = 8
  std::cout << "inner3 = " << inner3.get_v() << std::endl;    // output: inner3 = 3

  boost::optional<Inner> option5;
  option5 = option4;   // output: Inner(const Inner& other)  -- make a copy (copy constructor)
  std::cout << "option4 = " << option4->get_v() << std::endl; // output: option4 = 3
  std::cout << "option5 = " << option5->get_v() << std::endl; // output: option5 = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值