2020-05-26 15:39:27 +00:00
|
|
|
#ifndef ARBUTILS_BORROWEDPTR_HPP
|
|
|
|
#define ARBUTILS_BORROWEDPTR_HPP
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
namespace ArbUt {
|
|
|
|
/// A borrowed pointer is used to indicate a pointer that is not owned by an object, but instead borrowed from
|
|
|
|
/// another owning object that is assumed to always be kept alive during the entire lifetime of the borrowing
|
|
|
|
/// object.
|
|
|
|
template <class T> class BorrowedPtr {
|
|
|
|
private:
|
|
|
|
T* _raw;
|
|
|
|
|
|
|
|
public:
|
|
|
|
inline BorrowedPtr<T>() : _raw(nullptr){};
|
|
|
|
inline BorrowedPtr<T>(T* ptr) : _raw(ptr){};
|
|
|
|
inline BorrowedPtr(const BorrowedPtr<T>& other) : _raw(other._raw){};
|
|
|
|
inline BorrowedPtr(const std::unique_ptr<T>& other) : _raw(other.get()){};
|
|
|
|
|
|
|
|
~BorrowedPtr() = default;
|
|
|
|
|
|
|
|
inline BorrowedPtr<T>& operator=(const BorrowedPtr<T>& rhs) {
|
|
|
|
_raw = rhs._raw;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
inline T* operator->() const noexcept { return _raw; }
|
|
|
|
inline T* GetRaw() const noexcept { return _raw; }
|
|
|
|
|
|
|
|
inline bool operator==(const BorrowedPtr& rhs) const { return _raw == rhs._raw; }
|
|
|
|
inline bool operator!=(const BorrowedPtr& rhs) const { return _raw != rhs._raw; }
|
|
|
|
|
|
|
|
[[nodiscard]] inline constexpr bool IsNull() const noexcept { return _raw == nullptr; }
|
|
|
|
|
|
|
|
template <class TCast> inline BorrowedPtr<TCast> As() const {
|
2020-05-26 17:40:08 +00:00
|
|
|
auto cast = dynamic_cast<TCast*>(_raw);
|
2020-05-26 15:39:27 +00:00
|
|
|
return BorrowedPtr<TCast>(cast);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <class TCast> inline bool TryAs(BorrowedPtr<TCast>& out) const {
|
2020-05-26 17:40:08 +00:00
|
|
|
auto cast = dynamic_cast<TCast*>(_raw);
|
2020-05-26 15:39:27 +00:00
|
|
|
if (cast == nullptr)
|
|
|
|
return false;
|
|
|
|
out = BorrowedPtr<TCast>(cast);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
template <class TCast> inline BorrowedPtr<TCast> ForceAs() const {
|
2020-05-26 17:40:08 +00:00
|
|
|
auto cast = reinterpret_cast<TCast*>(_raw);
|
2020-05-26 15:39:27 +00:00
|
|
|
return BorrowedPtr<TCast>(cast);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif // ARBUTILS_BORROWEDPTR_HPP
|