Created
May 17, 2018 07:31
-
-
Save mirekfranc/c936549431b6c5a2ff9b7042223a5ca5 to your computer and use it in GitHub Desktop.
c++17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <variant> | |
#include <iostream> | |
#include <ios> | |
#define print(x) do { std::cout << #x << ": " << std::boolalpha << (x) << std::endl; } while (0) | |
struct IsEmptyVisitor | |
{ | |
template<typename T> | |
bool operator()(const T&) const { return false; } | |
bool operator()(std::monostate) const { return true; } // struct nil {} would do as well | |
}; | |
template<typename T> | |
bool is_really_empty(const T& _variant) | |
{ | |
return _variant.index() == 0; | |
} | |
int main() | |
{ | |
std::variant<std::monostate, int, long> a; | |
const bool is_a_empty = std::visit(IsEmptyVisitor(), a); | |
print(is_a_empty); | |
const bool is_a_really_empty = is_really_empty(a); | |
print(is_a_really_empty); | |
std::variant<std::monostate, int, long> b(42); | |
const bool is_b_empty = std::visit(IsEmptyVisitor(), b); | |
print(is_b_empty); | |
const bool is_b_really_empty = is_really_empty(b); | |
print(is_b_really_empty); | |
std::variant<std::monostate, int, long> c(42L); | |
const bool is_c_empty = std::visit(IsEmptyVisitor(), c); | |
print(is_c_empty); | |
const bool is_c_really_empty = is_really_empty(c); | |
print(is_c_really_empty); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment