Mission Impossible / How to create datatypes which cannot contain invalid state

adrianimboden
4,598 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

For details, see: https://en.cppreference.com/w/cpp/utility/variant

std::variant
// {...}
#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);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content