-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstd_variant.cpp
More file actions
106 lines (90 loc) · 1.67 KB
/
std_variant.cpp
File metadata and controls
106 lines (90 loc) · 1.67 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct SOutput
{
void operator()(const int& i)
{
std::cout << i << std::endl;
}
void operator()(const double& d)
{
std::cout << d << std::endl;
}
void operator()(const std::string& s)
{
std::cout << s << std::endl;
}
};
struct STOutput
{
template<typename TYPE>
void operator()(const TYPE& v)
{
std::cout << v << std::endl;
}
};
struct STwice
{
template<typename TYPE>
void operator()(TYPE& v)
{
v *= 2;
}
template<>
void operator()(std::string& s)
{
s += s;
}
};
int main()
{
std::variant<int, double, std::string> x, y;
// assign value
x = 1;
y = "1.0";
// overwrite value
x = 2.0;
// check index
std::cout << "x - " << x.index() << std::endl;
std::cout << "y - " << y.index() << std::endl;
// read value
double d = std::get<double>(x);
std::string s = std::get<2>(y);
// error type
try
{
int i = std::get<int>(x);
}
catch (std::bad_variant_access e)
{
std::cerr << e.what() << std::endl;
}
// use get_if
int* i = std::get_if<int>(&x);
if (i == nullptr)
{
std::cout << "wrong type" << std::endl;
}
else
{
std::cout << "value is " << *i << std::endl;
}
// visit
std::visit(SOutput(), y);
std::visit(STwice(), x);
std::visit(STwice(), y);
std::visit(STOutput(), x);
std::visit(
[](const auto& v) {std::cout << v << std::endl; },
y);
// vector
using var_t = std::variant<int, double, std::string>;
std::vector<var_t> vData = { 1, 2.0, "hi" };
for (var_t& v : vData)
{
std::visit(STwice(), v);
std::visit(SOutput(), v);
}
}