This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
vector<MyTemplate<MyClass>> not possible?
- From: "Evert, F.K. van" <F dot K dot vanEvert at plant dot wag-ur dot nl>
- To: "'gcc-help at gcc dot gnu dot org'" <gcc-help at gcc dot gnu dot org>
- Date: Fri, 20 Sep 2002 09:29:03 +0200
- Subject: vector<MyTemplate<MyClass>> not possible?
When I put instances of a template-derived class in a STL vector, g++ gives
me the following error message (Cygwin/g++3.2 as well as Suse8.0/g++2.95.3):
/usr/include/c++/3.2/bits/stl_construct.h:78: passing `const SmartPtr<CX>'
as
`this' argument of `SmartPtr<T>::operator T*() [with T = CX]' discards
qualifiers
I have seen similar error messages reported about auto_ptr derived classes
in STL containers, but my template class seems to have all the required
methods.
The code below compiles and runs fine with VC++ and BC++ (Kylix3/Suse8.0). I
would greatly appreciate any help that you can offer.
Regards,
Frits
===== main file ===========================================================
#include <stdio.h>
#include <vector>
template <class T> class SmartPtr
{
private:
T* m_pI;
public:
SmartPtr(T* p = NULL)
{
m_pI = p;
if (m_pI != NULL)
m_pI->AddRef();
}
~SmartPtr()
{
if (m_pI != NULL)
{
T* old = m_pI;
m_pI = NULL;
old->Release();
}
}
SmartPtr(const SmartPtr& r) throw()
{
m_pI = r.m_pI;
if (m_pI != NULL)
m_pI->AddRef();
}
SmartPtr& operator=(const SmartPtr& lp)
{
if (m_pI != lp.m_pI)
{
T* pOld = m_pI ;
m_pI = lp.m_pI ;
if (m_pI != NULL)
{
m_pI->AddRef() ;
}
if (pOld != NULL)
{
pOld->Release() ;
}
}
return *this;
}
T* operator->() { return m_pI; }
T** operator&() { return &m_pI ;}
T& operator*() { return *m_pI; }
operator T*() { return m_pI ;}
};
class CX {
public:
CX() { printf("CX::CX()\n"); cnt = 0; }
~CX() { printf("CX::~CX()\n"); }
void AddRef() { ++cnt; }
void Release() { --cnt; if (cnt==0) delete this; }
private:
long cnt;
};
typedef SmartPtr<CX> XPtr;
int main()
{
CX* px = new CX();
XPtr sp(px);
std::vector<XPtr> v;
v.push_back(sp); // THIS IS THE LINE THAT OFFENDS G++
return 0;
}
F.K. van Evert
Plant Research International
Phone (+31) 317-475957, Fax -423110