Skip to content

Instantly share code, notes, and snippets.

@mrshpot
Created December 7, 2015 18:41
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 mrshpot/cea4e9c517c12cbae82f to your computer and use it in GitHub Desktop.
Save mrshpot/cea4e9c517c12cbae82f to your computer and use it in GitHub Desktop.
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 &nothing)
: 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 &nothing)
{
this->valid = false;
this->value = T();
}
bool operator==(const Nothing &nothing)
{
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