query/include/matador/object/object_ptr.hpp

59 lines
1.6 KiB
C++

#ifndef OBJECT_PTR_HPP
#define OBJECT_PTR_HPP
#include "matador/utils/identifier.hpp"
#include "matador/object/object_proxy.hpp"
#include "matador/object/primary_key_resolver.hpp"
#include <memory>
namespace matador::object {
template <typename Type>
class object_ptr {
public:
object_ptr()
: ptr_(std::make_shared<object_proxy<Type>>()) {}
explicit object_ptr(Type *obj)
: ptr_(std::make_shared<object_proxy<Type>>(obj))
, pk_(primary_key_resolver::resolve_object(*obj).pk) {}
object_ptr(const object_ptr &other) : ptr_(other.ptr_) {}
object_ptr(object_ptr &&other) noexcept : ptr_(std::move(other.ptr_)) {}
object_ptr &operator=(const object_ptr &other) = default;
object_ptr &operator=(object_ptr &&other) = default;
using value_type = Type;
Type* operator->() const { return ptr_->pointer(); }
Type& operator*() { return ptr_->ref(); }
const Type& operator*() const { return ptr_->ref(); }
[[nodiscard]] bool empty() const { return ptr_->pointer() == nullptr; }
void reset(Type *obj) {
ptr_->reset(obj);
pk_ = primary_key_resolver::resolve_object(*obj).pk;
}
Type* get() const { return static_cast<Type*>(ptr_->pointer()); }
operator bool() { return valid(); }
bool valid() { return ptr_ != nullptr; }
[[nodiscard]] const utils::identifier& primary_key() const { return pk_; }
void primary_key(const utils::identifier &pk) { pk_ = pk; }
private:
std::shared_ptr<object_proxy<Type>> ptr_{};
utils::identifier pk_;
};
template<typename>
struct is_object_ptr : std::false_type
{};
template<typename Type>
struct is_object_ptr<object_ptr<Type>> : std::true_type
{};
}
#endif //OBJECT_PTR_HPP