1 // Cpp.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
2 //
3
4 #include <iostream>
5 #include <variant>
6 #include <any>
7 #include <string>
8 #include <optional>
9
10 using namespace std;
11 struct Visitor
12 {
13 void operator()(int m) {
14 cout << m << endl;
15 }
16 void operator()(string m) {
17 cout << m.data() << endl;
18 }
19 void operator()(float m) {
20 cout << m << endl;
21 }
22 };
23 std::optional<int> asInt(const std::string& s)
24 {
25 try
26 {
27 return std::stoi(s);
28 }
29 catch (...)
30 {
31 return std::nullopt;
32 }
33 }
34 int mains()
35 {
36 //variant 的好处是可以作为函数返回值
37 using va = std::variant<std::string, int, float>;
38 va v = 23;
39 cout << std::get<int>(v);
40 va v2 = "this is hello";
41 cout << std::get<string>(v2).data();
42 //std::visit 访问variant
43 any data = "this is any data 12";
44 v = 23;
45 std::visit(Visitor(), v); //23
46 v = "this is visitor";
47 std::visit(Visitor(), v); //"this is visitor"
48 v = 3.14157f;
49 std::visit(Visitor(), v); //3.14159
50 //any
51 std::any a = 2;
52 cout << endl << a.type().name() << endl;
53 a = "string";
54 cout << endl << a.type().name() << endl;
55 a = nullptr;
56 cout << endl << a.type().name() << endl;
57 if (nullptr == std::any_cast<std::nullptr_t>(a))
58 {
59 cout << "nullptr" << endl;
60 }
61
62 string tstr = "this is my str";
63 //string_view 不会创建tstr的副本
64 std::string_view view = tstr;
65 cout << view.data() << endl; //this is my str
66 tstr = "i changed it";
67 cout << view.data() << endl; //i changed it
68 //条件内声明变量
69 int m = 12;
70 if (int j = 23; j < 24)
71 {
72 cout << j;
73 }
74 //
75 // convert string to int if possible:
76 /*std::optional<int> asInt(const std::string& s)
77 {
78 try
79 {
80 return std::stoi(s);
81 }
82 catch (...)
83 {
84 return std::nullopt;
85 }
86 }*/
87 for (auto s : { "42", " 077", "hello", "0x33" })
88 {
89 std::optional<int> oi = asInt(s);
90 if (oi.emplace()) { //.has_value()
91 std::cout << "convert '" << s << "' to int: " << *oi << "\n";
92 }
93 else {
94 std::cout << "can't convert '" << s << "' to int\n";
95 }
96 }
97 std::optional<int> opt1 = std::make_optional(23);
98 std::optional<int> opt2 = 22;
99 //访问值*opt2 或者opt2.value()
100 cout << *opt2 << endl; //opt2
101 cout << opt2.value()<<endl; //opt2
102 opt2.emplace(34); //重新赋值
103 cout << *opt2 << endl; //34
104 cout << opt2.value()<<endl; //34
105 opt2.reset(); //清空
106 //opt2.value(); //为nullopt时,调用value报异常
107 cout << opt2.value()<<endl;
108
109 }