T
Thomas Lorenz
Hello,
im working on a problem related to smart pointers. If the following is
legal C++
A* a(new A());
B* b;
b = a;
I want to be able to do the following:
Ptr<A> a(new A());
Ptr<B> b;
b = a;
with equivalent semantics. Eventually, I came up with the following
"solution", involving a strange friend declaration:
template<class T>
class Ptr {
private:
T* m_pObject;
public:
// Constructors etc. removed for simplicity
template<class U>
inline friend void copy(Ptr<T>& to, Ptr<U>& from)
{
to.m_pObject = from.m_pObject;
};
// Curious trick
template<class U>
friend void copy(Ptr<U>&, Ptr<T>&);
template<class U>
inline Ptr(Ptr<U>& rhs)
: m_pObject(0)
{
copy(*this, rhs);
}
template<class U>
inline Ptr<T> operator=(Ptr<U>& rhs)
{
copy(*this,rhs);
return *this;
}
}
This works quite well using the MS 7.0 compiler. But I really don't know
why this "trick" enables copy() to access private members of Ptr<A> and
Ptr<B>. I've got a strange feeling this isn't supposed to work.
Oh, and the compiler produces "internal errors" if I try to repeat this
trick in Ptr with other functions...
Any ideas?
Thomas
im working on a problem related to smart pointers. If the following is
legal C++
A* a(new A());
B* b;
b = a;
I want to be able to do the following:
Ptr<A> a(new A());
Ptr<B> b;
b = a;
with equivalent semantics. Eventually, I came up with the following
"solution", involving a strange friend declaration:
template<class T>
class Ptr {
private:
T* m_pObject;
public:
// Constructors etc. removed for simplicity
template<class U>
inline friend void copy(Ptr<T>& to, Ptr<U>& from)
{
to.m_pObject = from.m_pObject;
};
// Curious trick
template<class U>
friend void copy(Ptr<U>&, Ptr<T>&);
template<class U>
inline Ptr(Ptr<U>& rhs)
: m_pObject(0)
{
copy(*this, rhs);
}
template<class U>
inline Ptr<T> operator=(Ptr<U>& rhs)
{
copy(*this,rhs);
return *this;
}
}
This works quite well using the MS 7.0 compiler. But I really don't know
why this "trick" enables copy() to access private members of Ptr<A> and
Ptr<B>. I've got a strange feeling this isn't supposed to work.
Oh, and the compiler produces "internal errors" if I try to repeat this
trick in Ptr with other functions...
Any ideas?
Thomas