-
Notifications
You must be signed in to change notification settings - Fork 0
/
variant.cpp
42 lines (34 loc) · 1.14 KB
/
variant.cpp
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
// Guideline 17: Consider std::variant for Implementing Visitors
#include <cstdlib>
#include <iostream>
#include <string>
#include <variant>
struct Print
{
void operator()(int value) const
{
std::cout << "int: " << value << '\n';
}
void operator()(double value) const
{
std::cout << "double: " << value << '\n';
}
void operator()(std::string const &value) const
{
std::cout << "string: " << value << '\n';
}
};
int main()
{
// Creates a default variant that contains an 'int' initialized to 0
std::variant<int, double, std::string> v{};
v = 42; // Assigns the 'int' 42 to the variant
v = 3.14; // Assigns the 'double' 3.14 to the variant
v = 2.71F; // Assigns a 'float', which is promoted to 'double'
v = "Bjarne"; // Assigns the string literal 'Bjarne' to the variant
v = 43; // Assigns the 'int' 43 to the variant
int const i = std::get<int>(v); // Direct access to the value
int *const pi = std::get_if<int>(&v); // Direct access to the value
std::visit(Print{}, v); // Applying the Print visitor
return EXIT_SUCCESS;
}