提升从字符串到 uint 的可选转换问题

问题描述

有人能解释为什么第一个转换有效而第二个可选的没有吗?

// 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
}

谢谢。

解决方法

boost::optional 有点像一个指针。它的名称,在本例中为 opt,可以转换为 bool,如果它有值则为真,否则为假。这就是 std::cout<<opt; 打印 1 的原因。要从可选中获取值,您可以像

一样“取消引用”它
std::cout << *opt;

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