【问题标题】:Boost optional conversion from string to uint problem提升从字符串到 uint 的可选转换问题
【发布时间】:2021-03-16 20:54:04
【问题描述】:

有人能解释一下为什么第一次转换有效而第二次使用 optional 无效吗?

// Example program
#include <iostream>
#include <string>
#include <boost/optional.hpp>

int main()
{
  std::string x = "16";
  uint16_t t =  (uint16_t)std::stoi(x);
  std::cout<<t; // prints 16
  
  std::string x2  = "16";
  boost::optional<uint16_t> opt =  (uint16_t)std::stoi(x2);
  std::cout<<opt; // prints 1
}

谢谢。

【问题讨论】:

    标签: c++ c++11 c++14 c++17


    【解决方案1】:

    boost::optional 有点像指针。它的名称,在本例中为opt,可以转换为布尔值,如果它有值则为真,否则为假。这就是std::cout&lt;&lt;opt; 打印1 的原因。要从可选项中获取值,您可以像“取消引用”它一样

    std::cout << *opt;
    

    现在你得到的是16 而不是1

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 2011-05-11
      • 2016-03-18
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      相关资源
      最近更新 更多