mirror-chatterino2/src/common/NullablePtr.hpp

74 lines
1.2 KiB
C++
Raw Normal View History

2018-06-24 11:45:30 +02:00
#pragma once
2018-08-02 14:23:27 +02:00
#include <type_traits>
2018-06-24 11:45:30 +02:00
namespace chatterino {
template <typename T>
class NullablePtr
{
public:
NullablePtr()
: element_(nullptr)
{
}
NullablePtr(T *element)
: element_(element)
{
}
T *operator->() const
{
assert(this->hasElement());
return element_;
}
2018-08-06 18:25:47 +02:00
typename std::add_lvalue_reference<T>::type operator*() const
2018-06-24 11:45:30 +02:00
{
assert(this->hasElement());
return *element_;
}
T *get() const
{
assert(this->hasElement());
return this->element_;
}
bool isNull() const
{
return this->element_ == nullptr;
}
bool hasElement() const
{
return this->element_ != nullptr;
}
operator bool() const
{
return this->hasElement();
}
2018-08-02 14:23:27 +02:00
bool operator!() const
{
return !this->hasElement();
}
2018-08-06 21:17:03 +02:00
template <typename X = T,
typename = std::enable_if_t<!std::is_const<X>::value>>
2018-08-02 14:23:27 +02:00
operator NullablePtr<const T>() const
{
return NullablePtr<const T>(this->element_);
}
2018-06-24 11:45:30 +02:00
private:
T *element_;
};
} // namespace chatterino