Photon Engine 2.0.0-beta
A physically based renderer.
Loading...
Searching...
No Matches
TAnyPtr.h
Go to the documentation of this file.
1#pragma once
2
3#include <utility>
4#include <cstddef>
5#include <type_traits>
6#include <typeindex>
7
8namespace ph
9{
10
15template<bool IS_CONST>
16class TAnyPtr final
17{
18public:
20
21 TAnyPtr(std::nullptr_t ptr);
22
23 template<typename T>
24 TAnyPtr(T* ptr);
25
26 template<typename T>
27 auto* get() const;
28
29 operator bool () const;
30
31 template<typename T>
32 operator T* () const;
33
34private:
35 using PointerType = std::conditional_t<IS_CONST, const void*, void*>;
36
37 PointerType m_pointer;
38 std::type_index m_pointedType;
39};
40
44
48
49template<bool IS_CONST>
51 : TAnyPtr(nullptr)
52{}
53
54template<bool IS_CONST>
55inline TAnyPtr<IS_CONST>::TAnyPtr(std::nullptr_t /* ptr */)
56 : m_pointer(nullptr)
57 , m_pointedType(typeid(std::nullptr_t))
58{}
59
60template<bool IS_CONST>
61template<typename T>
62inline TAnyPtr<IS_CONST>::TAnyPtr(T* const ptr)
63 : m_pointer(ptr)
64 , m_pointedType(typeid(T))
65{
66 static_assert(sizeof(T) == sizeof(T),
67 "Input must be a complete type.");
68}
69
70template<bool IS_CONST>
71template<typename T>
72inline auto* TAnyPtr<IS_CONST>::get() const
73{
74 // Also handles the case where `const` is explicitly specified in `T`
75 using ReturnType = std::conditional_t<IS_CONST, const T, T>;
76
77 // Important: type must be exactly equal for the cast to have defined behavior
78 if(m_pointedType == typeid(T))
79 {
80 return static_cast<ReturnType*>(m_pointer);
81 }
82 else
83 {
84 return static_cast<ReturnType*>(nullptr);
85 }
86}
87
88template<bool IS_CONST>
89inline TAnyPtr<IS_CONST>::operator bool () const
90{
91 return m_pointer != nullptr;
92}
93
94template<bool IS_CONST>
95template<typename T>
97{
98 // Note that we could, of course, write a better return type that matches `IS_CONST`. Here a more
99 // general type `T*` is used, so we could detect potential conversion errors here and provide
100 // a more friendly error message.
101 //
102 static_assert(!(IS_CONST && !std::is_const_v<T>),
103 "Cannot convert a const pointer to non-const.");
104
105 return get<T>();
106}
107
108}// end namespace ph
A type-safe, lightweight wrapper for any raw pointer type. Using std::any with a raw pointer type cou...
Definition TAnyPtr.h:17
auto * get() const
Definition TAnyPtr.h:72
TAnyPtr(std::nullptr_t ptr)
Definition TAnyPtr.h:55
TAnyPtr()
Definition TAnyPtr.h:50
TAnyPtr(T *ptr)
Definition TAnyPtr.h:62
The root for all renderer implementations.
Definition EEngineProject.h:6
Definition TAABB2D.h:96