File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments