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
You can exploit the fact that literal
NULL/0can be auto-cast to any pointer type. Create a type that is NOTT, and a constructor which takes a single pointer to that type which nobody will ever use. Now you can handlePtrWrapper<T> x(NULL);explicitly.Of course as others have said, this is only going to work if
NULLis known at compile-time.