Reputation: 309
I'd like a pointer wrapper class that acts just like a raw pointer but also saves a special integer along with the pointer (Type's index in the array it came from)
I managed to have it behave mostly like a pointer. I am aware that the pointer comparison solution might not be optimal but that's not my main problem. I want the wrapper to be constructed with 2 parameters(pointer,indexToArr), unless the pointer is NULL - then I don't care about indexToArr.
The problem I'm trying to solve is how to allow returning NULL just like a normal pointer allows. current solution uses an ASSERT. But I want something that works in compile-time. something in the spirit of a specialized template method - allowing only NULL as its argument.
Current version:
class PtrWrapper
{
public:
PtrWrapper(Type* ptr, int indToArr)
: m_ptr(ptr), m_indexToArr(indToArr){}
//allow returning NULL, only NULL
PtrWrapper(Type* ptr) : m_ptr(NULL), m_indexToArr(-1) {ASSERT(ptr == NULL);}
Type* operator->() const {return m_ptr;}
Type& operator*() const {return *m_ptr;}
int IndexToArr() const {return m_indexToArr;}
//for pointer comparison
operator Type*() const {return m_ptr;}
private:
Type* m_ptr;
int m_indexToArr;
};
Any ideas, suggestions?
Thanks, Leo
Upvotes: 4
Views: 5100
Reputation: 36896
template<typename Type>
class PtrWrapper
{
typedef struct { } NotType;
public:
Ptr() { }
Ptr(const NotType* nullPtr) { }
Ptr(Type* p, int index) { }
};
You can exploit the fact that literal NULL
/ 0
can be auto-cast to any pointer type. Create a type that is NOT T
, and a constructor which takes a single pointer to that type which nobody will ever use. Now you can handle PtrWrapper<T> x(NULL);
explicitly.
Of course as others have said, this is only going to work if NULL
is known at compile-time.
Upvotes: 5
Reputation: 32520
Simply make a default constructor with no arguments that initializes your pointer to NULL, but make sure to have some checks in your operator*
and operator->
for a NULL pointer.
Do the following:
PtrWrapper(Type* ptr) : m_ptr(ptr), m_indexToArr(0) {ASSERT(ptr != NULL);}
PtrWrapper() : m_ptr(NULL), m_indexToArr(-1) {ASSERT(ptr == NULL);}
Upvotes: 1