Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2012 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4268883 to your computer and use it in GitHub Desktop.
Save anonymous/4268883 to your computer and use it in GitHub Desktop.
An attempt at a polymorphic Maybe type in C++. Includes `fromMaybe` function. Attempted a `bind` function but it turns out pointers to template functions aren't possible. Maybe C++ lambdas or function objects can help here but I'll look at that some other time.
#include <iostream>
// Polymorphic Maybe type.
template <typename T>
class Maybe
{
public:
// Returns True if Maybe contains a value.
virtual bool isJust() = 0;
// Returns the value if Just. Throws exception if Nothing.
virtual T fromJust() = 0;
};
// Just option.
template <typename T>
class Just : public Maybe<T>
{
// Stored value.
T v;
public:
Just(T value)
{
this->v = value;
}
virtual bool isJust()
{
return true;
}
virtual T fromJust()
{
return this->v;
}
};
// Nothing option.
template <typename T>
class Nothing : public Maybe<T>
{
public:
Nothing() {};
virtual bool isJust()
{
return false;
}
virtual T fromJust()
{
throw new std::exception("fromJust: Maybe is Nothing");
}
};
// Converts a `Maybe a` into an `a`, using a default value if Nothing.
template <typename T>
T fromMaybe(T def, Maybe<T> *mv)
{
return mv->isJust() ? mv->fromJust() : def;
}
int main (int argc, const char * argv[])
{
// Create some Maybe objects.
Maybe<int> *myMaybe1 = new Just<int>(5);
Maybe<int> *myMaybe2 = new Nothing<int>();
// Print them out, defulting to 0 if Nothing.
std::cout << fromMaybe<int>(0, myMaybe1) << std::endl;
std::cout << fromMaybe<int>(0, myMaybe2) << std::endl;
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment