Skip to content

Commit bdedddb

Browse files
authored
Update 007_any_any.cpp
1 parent eb1ee8c commit bdedddb

1 file changed

Lines changed: 45 additions & 1 deletion

File tree

cpp_17/007_any_any.cpp

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,45 @@
1-
1
1+
#include <any>
2+
#include <iostream>
3+
4+
int main()
5+
{
6+
std::cout << std::boolalpha;
7+
8+
// any type
9+
std::any a = 1;
10+
std::cout << a.type().name() << ": " << std::any_cast<int>(a) << '\n';
11+
a = 3.14;
12+
std::cout << a.type().name() << ": " << std::any_cast<double>(a) << '\n';
13+
a = true;
14+
std::cout << a.type().name() << ": " << std::any_cast<bool>(a) << '\n';
15+
16+
// bad cast
17+
try
18+
{
19+
a = 1;
20+
std::cout << std::any_cast<float>(a) << '\n';
21+
}
22+
catch (const std::bad_any_cast& e)
23+
{
24+
std::cout << e.what() << '\n';
25+
}
26+
27+
// has value
28+
a = 1;
29+
if (a.has_value())
30+
{
31+
std::cout << a.type().name() << '\n';
32+
}
33+
34+
// reset
35+
a.reset();
36+
if (!a.has_value())
37+
{
38+
std::cout << "no value\n";
39+
}
40+
41+
// pointer to contained data
42+
a = 1;
43+
int* i = std::any_cast<int>(&a);
44+
std::cout << *i << "\n";
45+
}

0 commit comments

Comments
 (0)