微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决提升从字符串到 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。