Skip to content

Instantly share code, notes, and snippets.

@xaedes
Created October 27, 2017 13:26
Show Gist options
  • Save xaedes/009d3e0edd64772ba691b86164723533 to your computer and use it in GitHub Desktop.
Save xaedes/009d3e0edd64772ba691b86164723533 to your computer and use it in GitHub Desktop.
Test
// Example program
#include <iostream>
#include <string>
#include <ostream>
template<typename T>
class Maybe
{
public:
static Maybe Just(const T& just)
{
return Maybe(just);
}
static Maybe Just()
{
T empty;
return Maybe(empty);
}
static Maybe Nothing()
{
return Maybe();
}
Maybe(const Maybe<T>& copyFrom)
: m_valid(false)
{
if(copyFrom)
{
just(copyFrom.value());
}
}
Maybe(const T& just)
: m_value(just)
, m_valid(true)
{}
template <typename C>
Maybe(Maybe<C>& castFrom) //Converting constructor
: m_valid(false)
{
C* source = castFrom.ptr();
T* target = dynamic_cast<T*>(source);
if(target)
{
just(*target);
}
}
Maybe()
: m_valid(false)
{}
~Maybe()
{}
const T& value() const
{
return m_value;
}
T* ptr()
{
if (m_valid)
{
return &m_value;
}
else
{
return nullptr;
}
}
const T* operator->() const
{
if (m_valid)
{
return &m_value;
}
else
{
return nullptr;
}
}
T* operator->()
{
if (m_valid)
{
return &m_value;
}
else
{
return nullptr;
}
}
explicit operator bool() const
{
return containsValue();
}
bool containsNothing() const
{
return !m_valid;
}
bool containsValue() const
{
return m_valid;
}
bool isValid() const
{
return m_valid;
}
bool isEmpty() const
{
return !m_valid;
}
void clear()
{
T empty;
m_value = empty;
m_valid = false;
}
T& just(const T& just)
{
m_valid = true;
m_value = just;
return m_value;
}
T& just()
{
m_valid = true;
return m_value;
}
protected:
bool m_valid;
T m_value;
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const Maybe<T>& maybe)
{
os
<< "m_valid" << std::endl << maybe.isValid() << std::endl
<< "m_value" << std::endl << maybe.value() << std::endl << std::endl
;
return os;
}
class Base
{
public:
int m_base;
Base(int base)
: m_base(base)
{}
Base()
: Base(0)
{}
virtual ~Base(){}
};
class Derived : public Base
{
public:
int m_derived;
Derived(int base, int derived)
: Base(base)
, m_derived(derived)
{}
Derived()
: Derived(0,0)
{}
virtual ~Derived(){}
};
std::ostream& operator<<(std::ostream& os, const Base& base)
{
os
<< "m_base" << std::endl << base.m_base << std::endl << std::endl
;
return os;
}
std::ostream& operator<<(std::ostream& os, const Derived& derived)
{
os
<< "m_base" << std::endl << derived.m_base << std::endl << std::endl
<< "m_derived" << std::endl << derived.m_derived << std::endl << std::endl
;
return os;
}
using std::cout;
using std::endl;
int main()
{
Maybe<Derived> derived(Derived(1,2));
Maybe<Base> base(derived);
Maybe<Derived> derived2(base);
cout << "derived" << endl << derived;
cout << "base" << endl << base;
cout << "derived2" << endl << derived2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment