-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariant_example.cpp
More file actions
64 lines (55 loc) · 2.03 KB
/
variant_example.cpp
File metadata and controls
64 lines (55 loc) · 2.03 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
#include <string>
#include <iostream>
#include <variant>
struct SampleVisitor
{
void operator()(int i) const {
std::cout << "visit int: " << i << "\n";
}
void operator()(float f) const {
std::cout << "visit float: " << f << "\n";
}
void operator()(const std::string& s) const {
std::cout << "visit string: " << s << "\n";
}
};
int main()
{
std::variant<int, float, std::string> intFloatString;
static_assert(std::variant_size_v<decltype(intFloatString)> == 3);
// default initialized to the first alternative, should be 0
std::visit(SampleVisitor{}, intFloatString);
// index will show the currently used 'type'
std::cout << "index = " << intFloatString.index() << std::endl;
intFloatString = 100.0f;
std::cout << "index = " << intFloatString.index() << std::endl;
intFloatString = "hello super world";
std::cout << "index = " << intFloatString.index() << std::endl;
// try with get_if:
if (const auto intPtr (std::get_if<int>(&intFloatString)); intPtr)
std::cout << "int!" << *intPtr << "\n";
else if (const auto floatPtr (std::get_if<float>(&intFloatString)); floatPtr)
std::cout << "float!" << *floatPtr << "\n";
if (std::holds_alternative<int>(intFloatString))
std::cout << "the variant holds an int!\n";
else if (std::holds_alternative<float>(intFloatString))
std::cout << "the variant holds a float\n";
else if (std::holds_alternative<std::string>(intFloatString))
std::cout << "the variant holds a string\n";
// try/catch and bad_variant_access
try
{
auto f = std::get<float>(intFloatString);
std::cout << "float! " << f << "\n";
}
catch (std::bad_variant_access&)
{
std::cout << "our variant doesn't hold float at this moment...\n";
}
// visit:
std::visit(SampleVisitor{}, intFloatString);
intFloatString = 10;
std::visit(SampleVisitor{}, intFloatString);
intFloatString = 10.0f;
std::visit(SampleVisitor{}, intFloatString);
};