Skip to content

Commit da25020

Browse files
authored
Update 007_any_make_any.cpp
1 parent ade400b commit da25020

1 file changed

Lines changed: 35 additions & 1 deletion

File tree

‎cpp_17/007_any_make_any.cpp‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
1-
1
1+
#include <any>
2+
#include <complex>
3+
#include <functional>
4+
#include <iostream>
5+
#include <string>
6+
7+
int main()
8+
{
9+
auto a0 = std::make_any<std::string>("Hello, std::any!\n");
10+
auto a1 = std::make_any<std::complex<double>>(0.1, 2.3);
11+
12+
std::cout << std::any_cast<std::string&>(a0);
13+
std::cout << std::any_cast<std::complex<double>&>(a1) << '\n';
14+
15+
using lambda = std::function<void(void)>;
16+
17+
// Put a lambda into std::any. Attempt #1 (failed).
18+
std::any a2 = [] { std::cout << "Lambda #1.\n"; };
19+
std::cout << "a2.type() = \"" << a2.type().name() << "\"\n";
20+
21+
// any_cast casts to <void(void)> but actual type is not
22+
// a std::function..., but ~ main::{lambda()#1}, and it is
23+
// unique for each lambda. So, this throws...
24+
try {
25+
std::any_cast<lambda>(a2)();
26+
}
27+
catch (std::bad_any_cast const& ex) {
28+
std::cout << ex.what() << '\n';
29+
}
30+
31+
// Put a lambda into std::any. Attempt #2 (successful).
32+
auto a3 = std::make_any<lambda>([] { std::cout << "Lambda #2.\n"; });
33+
std::cout << "a3.type() = \"" << a3.type().name() << "\"\n";
34+
std::any_cast<lambda>(a3)();
35+
}

0 commit comments

Comments
 (0)