Mission Impossible / How to create datatypes which cannot contain invalid state
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
For details, see: https://en.cppreference.com/w/cpp/utility/variant
std::variant
1
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
// {
#include <variant>
int main() {
std::variant<int, std::string> num_or_str = 7;
if (std::holds_alternative<int>(num_or_str)) {
std::cout << std::get<int>(num_or_str) << "\n";
}
if (auto* p_num = std::get_if<int>(&num_or_str)) {
std::cout << *p_num << "\n";
}
std::visit(
[](auto streamable) {
if constexpr (std::is_same_v<decltype(streamable), int>) {
std::cout << streamable << "\n";
}
},
num_or_str);
std::visit(
overloaded{
[](int num) { std::cout << num << "\n"; },
[](std::string) {},
},
num_or_str);
std::visit([](auto streamable) { std::cout << streamable << "\n"; }, num_or_str);
struct PrintVisitor {
void operator()(int num) {
std::cout << "num: " << num << "\n";
}
void operator()(std::string str) {
std::cout << "str: " << str << "\n";
}
};
std::visit(PrintVisitor{}, num_or_str);
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content