-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariant.cpp
More file actions
67 lines (47 loc) · 1.24 KB
/
variant.cpp
File metadata and controls
67 lines (47 loc) · 1.24 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
#include <iostream>
#include <variant>
#include <any>
#include <optional>
#include <vector>
// methods
//
// index
//
// emplace
//
// others:
//
// holds_alternative
//
// get<>
// get_if<>
//
// visit
void print(int) { std::cout << "int" << std::endl; }
void print(double) { std::cout << "double" << std::endl; }
int main() {
using variant_t = std::variant<int,double>;
std::vector<variant_t> v;
v.emplace_back(1);
v.emplace_back(1.2);
for (auto& x : v)
if (std::holds_alternative<int>(x))
print(std::get<int>(x));
else if(std::holds_alternative<double>(x))
print(std::get<double>(x));
std::variant<int,float,const char*> data;
data = 0;
if (std::holds_alternative<float>(data))
std::cout << std::get<float>(data) << std::endl;
if (std::holds_alternative<const char*>(data))
std::cout << std::get<const char*>(data) << std::endl;
if (auto ptr = std::get_if<int>(&data))
std::cout << *ptr << std::endl;
if (auto ptr = std::get_if<float>(&data))
std::cout << *ptr << std::endl;
auto value = std::get<int>(data);
std::cout << value << std::endl;
value = std::get<0>(data);
std::cout << value << std::endl;
return 0;
}