-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcppvariant.cpp
More file actions
34 lines (29 loc) · 1.14 KB
/
cppvariant.cpp
File metadata and controls
34 lines (29 loc) · 1.14 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
#include <iostream>
#include <string>
#include <variant>
#include <algorithm>
int main() {
std::cout << "enter main" << std::endl;
std::variant<int, double, std::string> myVariant;
std::cout << "space: index in myVariant= " << myVariant.index() << std::endl;
myVariant = 42; // Assign an int
// Access the int
if (holds_alternative<int>(myVariant)) {
std::cout << "int: index in myVariant= " << myVariant.index() << std::endl;
std::cout << get<int>(myVariant) << std::endl;
}
myVariant = 3.14; // Assign a double
// Access the double
if (holds_alternative<double>(myVariant)) {
std::cout << "double: index in myVariant= " << myVariant.index() << std::endl;
std::cout << get<double>(myVariant) << std::endl;
}
//myVariant = "Hello, Variant!"; // Assign a string
myVariant.emplace<std::string>("Hello, Variant!");
// Access the string
if (holds_alternative<std::string>(myVariant)) {
std::cout << "String: index in myVariant= " << myVariant.index() << std::endl;
std::cout << "String: value= " << get<std::string>(myVariant) << std::endl;
}
return 0;
}