Skip to content

Instantly share code, notes, and snippets.

@argv0
Forked from anonymous/gist:4334155
Created December 19, 2012 03:33
Show Gist options
  • Save argv0/4334176 to your computer and use it in GitHub Desktop.
Save argv0/4334176 to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <stdexcept>
template <class T>
struct Maybe {
Maybe( const T& val ) : val_(val), valid_(true) { }
Maybe() : valid_(false) { }
const T& get() const {
if (valid_) return val_;
throw std::logic_error("lol type systems");
}
private:
T val_;
bool valid_;
};
template <class T>
Maybe<T> Just(const T& val) {
return Maybe<T>(val);
}
template <class T>
Maybe<T> Nothing() {
return Maybe<T>();
}
Maybe<int> isYouPositive(int x)
{
if (x > 0) return Just(x);
return Nothing<int>();
}
int main(void)
{
auto a = isYouPositive(1);
printf("%d\n", a.get());
auto b = isYouPositive(-1);
printf("%d\n", b.get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment