Boost optional conversion from string to uint 问题

Boost optional conversion from string to uint problem

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

// 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,可以转换为布尔值,如果它有值则为真,否则为假。这就是 std::cout<<opt; 打印 1 的原因。要从可选中获取值,您可以像

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

现在你得到 16 而不是 1