Skip to content

Instantly share code, notes, and snippets.

@nem0
Created May 27, 2017 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nem0/1394f6935151322184847797e1afc249 to your computer and use it in GitHub Desktop.
Save nem0/1394f6935151322184847797e1afc249 to your computer and use it in GitHub Desktop.
Compile time safe nullable/optional
#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