如何在cpp中将std::Optional<unsigned>转换为无符号?

问题描述 投票:0回答:1

有没有办法将可选的无符号变量类型转换为无符号

#include <bits/stdc++.h> using namespace std; int main() { vector<int> vec = { 10, 20, 30 }; std::optional<unsigned> check = 200; std::cout << check << std::endl; std::cout << check.emplace() << std::endl; return 0; }
在上面的函数中,当我尝试打印

check

(可选变量)时,出现以下错误:

main.cpp: In function ‘int main()’: main.cpp:15:15: error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘std::optional’) 15 | std::cout << check << std::endl; | ~~~~~~~~~ ^~ ~~~~~ | | | | | std::optional<unsigned int> | std::ostream {aka std::basic_ostream<char>}
下面是我尝试使用 emplace 打印时的结果,因为 

check.emplace()

 是:

#include <bits/stdc++.h> using namespace std; int main() { vector<int> vec = { 10, 20, 30 }; std::optional<unsigned> check = 200; // std::cout << check << std::endl; std::cout << check.emplace() << std::endl; return 0; }
结果:

0 ...Program finished with exit code 0 Press ENTER to exit console.
上面的例子只是为了演示我的问题。实际程序有 

std::optional<unsigned> check

 是因为它带有默认参数是可选的。当用户传递不同的参数时,我想将 
arg
 传递给以 
unsigned
 作为参数的函数。

有人可以解释为什么会出现上述问题以及我能做些什么来解决它吗?

c++ casting option-type
1个回答
0
投票
关于第一行:

std::cout << check << std::endl;

std::optional

 转换为其包含的值时,需要处理它为空的情况。
您可以使用
std::Optional::value_or 来实现:

std::cout << check.value_or(0) << std::endl;
关于第二行:

std::cout << check.emplace() << std::endl;
它将一个值存储在 

std::optional

 中,并返回对此值的引用。由于您没有提供任何具体值,因此将使用默认值 
0
,这就是您看到的打印内容。

© www.soinside.com 2019 - 2024. All rights reserved.