From 79d6bd9a227f9c07b2a1c3e55d9e06d8b8306f39 Mon Sep 17 00:00:00 2001 From: Jacques Lucke Date: Fri, 18 Dec 2020 13:26:08 +0100 Subject: Functions: add generic pointer class for const pointers This adds a GPointer class, which is mostly the same as GMutablePointer. The main difference is that GPointer references const data, while GMutablePointer references non-const data. --- source/blender/functions/FN_generic_pointer.hh | 55 +++++++++++++++++++++++- source/blender/functions/FN_generic_value_map.hh | 2 +- 2 files changed, 54 insertions(+), 3 deletions(-) (limited to 'source') diff --git a/source/blender/functions/FN_generic_pointer.hh b/source/blender/functions/FN_generic_pointer.hh index 5c2b611c614..2bd66daa7fe 100644 --- a/source/blender/functions/FN_generic_pointer.hh +++ b/source/blender/functions/FN_generic_pointer.hh @@ -21,7 +21,7 @@ namespace blender::fn { /** - * A generic pointer whose type is only known at runtime. + * A generic non-const pointer whose type is only known at runtime. */ class GMutablePointer { private: @@ -58,7 +58,7 @@ class GMutablePointer { template T *get() const { BLI_assert(this->is_type()); - return reinterpret_cast(data_); + return static_cast(data_); } template bool is_type() const @@ -73,4 +73,55 @@ class GMutablePointer { } }; +/** + * A generic const pointer whose type is only known at runtime. + */ +class GPointer { + private: + const CPPType *type_ = nullptr; + const void *data_ = nullptr; + + public: + GPointer() = default; + + GPointer(GMutablePointer ptr) : type_(ptr.type()), data_(ptr.get()) + { + } + + GPointer(const CPPType *type, const void *data = nullptr) : type_(type), data_(data) + { + /* If there is data, there has to be a type. */ + BLI_assert(data_ == nullptr || type_ != nullptr); + } + + GPointer(const CPPType &type, const void *data = nullptr) : type_(&type), data_(data) + { + } + + template GPointer(T *data) : GPointer(&CPPType::get(), data) + { + } + + const void *get() const + { + return data_; + } + + const CPPType *type() const + { + return type_; + } + + template const T *get() const + { + BLI_assert(this->is_type()); + return static_cast(data_); + } + + template bool is_type() const + { + return type_ != nullptr && type_->is(); + } +}; + } // namespace blender::fn diff --git a/source/blender/functions/FN_generic_value_map.hh b/source/blender/functions/FN_generic_value_map.hh index 2c1b37c0461..a9f2dc8a868 100644 --- a/source/blender/functions/FN_generic_value_map.hh +++ b/source/blender/functions/FN_generic_value_map.hh @@ -66,7 +66,7 @@ template class GValueMap { /* Add a value to the container that is copy constructed from the given value. The caller remains * responsible for destructing and freeing the given value. */ - template void add_new_by_copy(ForwardKey &&key, GMutablePointer value) + template void add_new_by_copy(ForwardKey &&key, GPointer value) { const CPPType &type = *value.type(); void *buffer = allocator_.allocate(type.size(), type.alignment()); -- cgit v1.2.3