Created
December 7, 2015 18:41
-
-
Save mrshpot/cea4e9c517c12cbae82f to your computer and use it in GitHub Desktop.
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
class Nothing; | |
template <typename T> | |
class Optional | |
{ | |
T value; | |
bool valid; | |
Optional(const T &value) | |
: value(value) | |
, valid(true) | |
{ | |
} | |
public: | |
Optional() | |
: valid(false) | |
{ | |
} | |
Optional(const Nothing ¬hing) | |
: valid(false) | |
{ | |
} | |
static Optional<T> make_value(const T &value) | |
{ | |
return Optional<T>(value); | |
} | |
Optional& operator=(const Optional &other) | |
{ | |
this->valid = other.valid; | |
if (valid) | |
this->value = other.value; | |
else | |
this->value = T(); | |
return *this; | |
} | |
Optional& operator=(const Nothing ¬hing) | |
{ | |
this->valid = false; | |
this->value = T(); | |
} | |
bool operator==(const Nothing ¬hing) | |
{ | |
return !valid; | |
} | |
~Optional() | |
{ | |
} | |
T& unwrap() | |
{ | |
if (!valid) abort(); | |
return value; | |
} | |
}; | |
template <typename T> | |
Optional<T> Value(const T &value) | |
{ | |
return Optional<T>::make_value(value); | |
} | |
class Nothing | |
{ | |
}; | |
/* Example */ | |
Optional<char> next_char(const char *str, int &pos) | |
{ | |
if (str[pos] != '\0') | |
return Value(str[pos++]); | |
else | |
return Nothing(); | |
} | |
void test_string(const char *str) | |
{ | |
int pos = 0; | |
do { | |
Optional<char> it = next_char(str, pos); | |
if (it == Nothing()) | |
{ | |
printf("\nEOF.\n"); | |
break; | |
} | |
else | |
{ | |
printf("%c", it.unwrap()); | |
} | |
} while (1); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
test_string("Hello, World!"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment