File tree Expand file tree Collapse file tree 1 file changed +48
-1
lines changed
Expand file tree Collapse file tree 1 file changed +48
-1
lines changed Original file line number Diff line number Diff line change 1- 1
1+ #include < string>
2+ #include < iostream>
3+ #include < any>
4+ #include < utility>
5+
6+ int main ()
7+ {
8+ // simple example
9+
10+ auto a = std::any (12 );
11+
12+ std::cout << std::any_cast<int >(a) << ' \n ' ;
13+
14+ try {
15+ std::cout << std::any_cast<std::string>(a) << ' \n ' ;
16+ }
17+ catch (const std::bad_any_cast& e) {
18+ std::cout << e.what () << ' \n ' ;
19+ }
20+
21+ // pointer example
22+
23+ if (int * i = std::any_cast<int >(&a)) {
24+ std::cout << " a is int: " << *i << ' \n ' ;
25+ } else if (std::string* s = std::any_cast<std::string>(&a)) {
26+ std::cout << " a is std::string: " << *s << ' \n ' ;
27+ } else {
28+ std::cout << " a is another type or unset\n " ;
29+ }
30+
31+ // advanced example
32+
33+ a = std::string (" hello" );
34+
35+ auto & ra = std::any_cast<std::string&>(a); // < reference
36+ ra[1 ] = ' o' ;
37+
38+ std::cout << " a: "
39+ << std::any_cast<const std::string&>(a) << ' \n ' ; // < const reference
40+
41+ auto b = std::any_cast<std::string&&>(std::move (a)); // < rvalue reference
42+
43+ // Note: 'b' is a move-constructed std::string,
44+ // 'a' is left in valid but unspecified state
45+
46+ std::cout << " a: " << *std::any_cast<std::string>(&a) // < pointer
47+ << " b: " << b << ' \n ' ;
48+ }
You can’t perform that action at this time.
0 commit comments