Original Post
I have a templated class that holds a pointer of the templated type, but I need to be able to cast that pointer into another template of the class. However, using visual C++ 6.0 I get either a compiler error saying that I can't use a class name as an expression, or that it can't figure out what I want on its own. So... what the heck? What am I doing wrong?
template<class T>
class Pointer
{
protected:
T* m_Held;
unsigned int* RefCount;
void Add()
{
if(RefCount)
{
++*RefCount;
}
else
{
RefCount = new unsigned int(1);
}
}
void Release()
{
if(RefCount)
{
--*RefCount;
if(*RefCount == 0)
{
delete RefCount;
delete m_Held;
}
}
}
Pointer(T* Obj, unsigned int* Count) : m_Held(Obj), RefCount(Count)
{
Add();
}
public:
Pointer(T* Obj) : m_Held(Obj), RefCount(0)
{
Add();
}
Pointer(const Pointer& rs) : m_Held(rs.m_Held), RefCount(rs.RefCount)
{
}
~Pointer()
{
Release();
}
Pointer& operator=(const Pointer& rs)
{
Release();
m_Held = rs.m_Held;
RefCount = rs.RefCount;
Add();
}
operator bool()
{
return m_Held != 0;
}
T* operator ->()
{
return m_Held;
}
template<class N>
Pointer<N> Cast()
{
return Pointer<N>(dynamic_cast<N*>(m_Held), RefCount);
}
};
class BaseObj;
class DerivObj : public BaseObj;
void main()
{
Pointer<BaseObj> Blah(new DerivObj);
//I would think this would work:
Pointer<DerivObj> Dude(Blah.Cast<DerivObj>());
//But I get C2275: 'DerivObj' : illegal use of this type as an expression
//So, just to try everything, I try taking that out:
Pointer<DerivObj> Dude(Blah.Cast());
//And I get C2738 : 'class Pointer<T> __thiscall Pointer<class BaseObj>::Cast(void)' : could not deduce template argument for 'N'
//Yeah, didn't think it would work.
}