Is there a way to typecast optional unsigned variable to unsigned
#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;
}
In the above function, when I tried to print check
(optional variable), I get the below error:
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>}
and below is the result when i tried using emplace to print as check.emplace()
is:
#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;
}
result:
0
...Program finished with exit code 0
Press ENTER to exit console.
The above example is just to demonstrate my issue. Actual program has std::optional<unsigned> check
is because its optional with a default parameter. When a user pass a different argument, I want to pass that arg
to a function which takes unsigned
as a parameter.
Can someone explain why the above issue and what could I do to fix it?