Created
May 27, 2017 00:28
-
-
Save nem0/1394f6935151322184847797e1afc249 to your computer and use it in GitHub Desktop.
Compile time safe nullable/optional
This file contains hidden or 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 <cstdio> | |
template <typename T> | |
class Nullable | |
{ | |
public: | |
Nullable(T* _val) : value(_val) {} | |
void operator=(const Nullable<T>& rhs) { value = rhs.value; } | |
template <typename F> | |
void is(F f) | |
{ | |
if (value) f(*value); | |
} | |
private: | |
T* value; | |
}; | |
int main() | |
{ | |
int x = 4; | |
Nullable<int> nullable_m(&x); | |
Nullable<int> nullable_n(nullptr); | |
nullable_m.is([&](auto val) { | |
printf("%d == %d", val, x); | |
}); | |
nullable_n.is([](auto val) { | |
printf("%d", val); | |
}); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment