Re: Defining a cast on a templated class
alan a 9crit :
On Nov 15, 5:32 am, Michael DOUBEZ <michael.dou...@free.fr> wrote:
You can overload the operators
template<class T>
cell<T>& operator+(cell<T>& lhs,const T& rhs)
{
return lhs+cell<T>(rhs);}
template<class T>
cell<T>& operator+(const cell<T>& lhs,const T& rhs)
{
return lhs+cell<T>(rhs);
}
Hmm. Just a question on how C++ handles the dealloc - when is the
object created in cell<T>(rhs) above destroyed?
I was doing something like this:
template<class T>
cell<T>& operator+(cell<T>& lhs, T& rhs)
{
cell<T> ret(lhs);
cell<T> rhsT(rhs);
return ret+=rhsT;
}
However the above would cause a segfault.
Yes, drop the return by reference and return by value; I had started
writing operator+= and changed to operator+ but forgot to change the
return value.
I have not actually compiled and tested the code.
Retaking the implementation I gave:
//implement here detail of body composite
namespace imp
{
//interface of cell body
template<class T>
struct cell_body
{
virtual ~cell_body(){}
virtual T get_value()const=0;
};
tyedef boost::shared_ptr<cell_body> cell_body_ptr;
I read the boost Smart Pointer manuals a bit, and it seems that it is
this which handles reference counting - all reference counting -
without actually having to modify (?) the classes to be reference
counted. Wow. I really have to read how this is implemented.
I used smart_ptr for simplicity. In your case, I guess an intrusive_ptr
would be more fitting since you don't need weak_ptr and the additionnal
overhead of external counter and it matches the semantic you intend
(cell should be aware they are referenced).
Michael