any_cast doc: https://en.cppreference.com/w/cpp/utility/any/any_cast

This blog explains the std::any_cast behavior. The std::any_cast is a template function that casts std::any to a reference to the type T stored in the std::any. The std::any_cast function is used to retrieve the value stored in the std::any object. The std::any_cast function is a non-throwing function. If the std::any object does not contain a value of type T, the function returns a null pointer.

Some examples are shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <any>

using namespace std;

int main() {
// explain the difference between auto& and auto
auto a1 = any(12); //necessary
a1 = string("test");
auto& s = any_cast<string&>(a1);
s[0] = "s";
cout << any_cast<string const&>(a1) << endl; // output sest
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <any>

using namespace std;

int main() {
auto a1 = any(12); //necessary
a1 = string("test");
auto s = any_cast<string>(a1);
s[0] = "s";
cout << any_cast<string const&>(a1) << endl; // output test
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <any>
#include <cassert>
#include <unordered_map>
#include <memory>
using namespace std;

void test1() {
auto a1 = any(12);
a1 = string("test");
auto& ra = any_cast<string&>(a1);
ra[0] = 's';
assert(any_cast<string const&>(a1) == "sest");
return ;

}

void test10() {
auto a1 = any(12);
a1 = string("test");
auto ra = any_cast<string>(a1); // cannot use auto& if any_cast<string>, will compliation error
ra[0] = 's';
assert(any_cast<string const&>(a1) == "test");
return ;

}

void test2() {
unordered_map<string, any> m;
m["s"] = string("test");
auto& ra = any_cast<string&>(m["s"]);
ra[0] = 's';
assert(any_cast<string const&>(m["s"]) == "sest");
//cout << s << endl;
return ;
}

int main() {
test1();
test10();
test2();
return 0;
}